gpt4 book ai didi

java - Arraylist 的 list.add() 中出现错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:17:50 24 4
gpt4 key购买 nike

我正在使用 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 的建议手动将所有原语装箱到对象。

关于java - Arraylist 的 list.add() 中出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17089729/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com