Java ArrayList 不兼容的类型

标签 java collections

我有一个问题。我正在尝试将相同类的对象添加到 ArrayList 中,但当我尝试检索它们时,我得到了不兼容的类型错误

import java.util.*;

public class Test{

Test(){
    main();
}

List test = new ArrayList();

public void main(){
    test.add(new Square(10));

    Iterator i = test.iterator();
    while(i.hasNext()){
        Square temp = i.next();
    }
}
}

最佳答案

是的 - 你没有在任何地方使用泛型,所以 i.next(); 就编译器而言只是返回 Object

选项:

  • 使用泛型
  • 转换为 Square:

    Square temp = (Square) i.next();
    

就我个人而言,我更喜欢使用泛型 - 在可以的地方拥有类型安全会更好 :)

// Not clear why this is an instance variable - and please make fields private :)
List<Square> test = new ArrayList<Square>();

public void main() {
    test.add(new Square(10));

    Iterator<Square> i = test.iterator();
    while(i.hasNext()) {
        Square temp = i.next();
        // Use square here
    }
}

两个旁白:

  • 增强的 for 循环可以取代您的 while 循环:

    for (Square square : test)
    
  • 有一个名为 main 且没有参数的 instance 方法很奇怪;更常见的是 public static void main(String[] args)。你在这里所做的并没有违法,只是很奇怪。

关于Java ArrayList 不兼容的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9290942/

相关文章:

java - Int String 格式问题

java - 将 JpaRepository 与 Spring Boot 一起使用

与集合和泛型相关的 Java 10 迁移问题

java - '列表<T >' may not contain type objects of type ' 对象'

delphi - 如何更新 TList<T> 中的数据?

java - Java 中的日期排序

java - Android 中从哪里获取 R.id.container?

java - 在 toString() 中使用继承/扩展的具体类名

java - 无法将包装在 JPanel 中的 JButton 添加到 JTable 中

.net - 是否需要封装Collections?