错误发生在Arraylist的list.add()中

我正在使用Eclipse JUno,我遇到了arraylist的.add()问题请帮助。我的代码是

import java.util.ArrayList; public class A { public static void main(String[] args) { ArrayList list=new ArrayList(); list.add(90); list.add(9.9); list.add("abc"); list.add(true); System.out.println(list); } } 

即将发生的错误是:

  Exception in thread "main" java.lang.Error: Unresolved compilation problems: The method add(int, Object) in the type ArrayList is not applicable for the arguments (int) The method add(Object) in the type ArrayList is not applicable for the arguments (double) The method add(Object) in the type ArrayList is not applicable for the arguments (boolean) at A.main(A.java:7) 

但这是奇怪的事情,那条线

  list.add("abc"); 

没有导致任何错误..列表的ADD方法采取一个参数,这是一个对象类型,然后为什么我面临这个问题,请帮助伙计..我搜索了很多,我没有得到任何解决方案。我必须做这个练习由于这个错误,我不能继续我的做法..

我想你使用的是java 1.5之前的版本。 Autoboxing在java 1.5中引入。 你的代码在java 1.5+上编译得很好。

编译为源1.4:

 javac -source 1.4 A.java A.java:7: error: no suitable method found for add(int) list.add(90); ^ method ArrayList.add(int,Object) is not applicable (actual and formal argument lists differ in length) method ArrayList.add(Object) is not applicable (actual argument int cannot be converted to Object by method invocation conversion) A.java:8: error: no suitable method found for add(double) list.add(9.9); ^ method ArrayList.add(int,Object) is not applicable (actual and formal argument lists differ in length) method ArrayList.add(Object) is not applicable (actual argument double cannot be converted to Object by method invocation conversion) A.java:10: error: no suitable method found for add(boolean) list.add(true); ^ method ArrayList.add(int,Object) is not applicable (actual and formal argument lists differ in length) method ArrayList.add(Object) is not applicable (actual argument boolean cannot be converted to Object by method invocation conversion) 3 errors 

1.5(或更高):

 javac -source 1.5 A.java warning: [options] bootstrap class path not set in conjunction with -source 1.5 Note: A.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. 1 warning 

建议你手动更新你的java或盒子所有原语到对象,如@SoulDZIN建议的那样。

适用于JDK 6

 public static void main(String[] args) { ArrayList list=new ArrayList(); list.add(90); list.add(9.9); list.add("abc"); list.add(true); System.out.println(list); } 

印刷结果 :[90,9.9,abc,true]。

如果你仍然使用比jdk 6更小的版本。请指定版本。

请注意,’add’方法对于数据类型失败:

int,double和boolean。

这些都是原始数据类型,而不是方法所期望的“对象”。 我相信这里没有发生自动装箱,因为你使用的是字面值,但我对此并不确定。 不过,要解决此问题,请使用每个基元的关联对象类型:

 ArrayList list=new ArrayList(); list.add(new Integer(90)); list.add(new Double(9.9)); list.add("abc"); list.add(new Boolean(true)); System.out.println(list); 

消息来源:经验

编辑:

我总是尝试指定我的Collection的类型,即使它是一个Object。

 ArrayList list = new ArrayList(); 

但是,如果您运行Java 1.4或更低版本,显然这不是一个好习惯。