【问题标题】:Difference in the type of "Array of Objects" AND "ArrayList of same Objects"? [duplicate]“对象数组”和“相同对象的数组列表”类型的区别? [复制]
【发布时间】:2014-06-18 02:55:00
【问题描述】:

我无法理解“对象数组”和“相同对象的数组列表”类型的区别。例如我有接口 X:

public interface X {

    public void implemntX();
}

类 XYZ 实现 X:

public class XYZ implements X{

@Override
public void implemntX() {
    // TODO Auto-generated method stub

}
}

以下代码完美运行:

X arraryOfX[] = new XYZ[10];

if(arraryOfX instanceof XYZ[]){
        System.out.println("arraryOfX is instanceOF XYZ[]");
    }else{
        System.out.println("arraryOfX is NOT instanceOF XYZ[]");
    }

Output: arraryOfX is instanceOF XYZ[]

但以下代码行给了我编译时错误:

ArrayList<X> arrayListOFX = new ArrayList<XYZ>();

ERROR: Type mismatch: cannot convert from ArrayList<XYZ> to ArrayList<X>

据我所知,ArrayList 内部使用数组,那么为什么类型不匹配错误会冒泡?

【问题讨论】:

  • 这个other answer 也可能有帮助,因为它提供了数组和通用集合之间的比较。
  • 顺便说一句,您有一个 array or references to ObjectsArrayList of references to Objects 相同的引用可以出现在两者中。

标签: java arrays arraylist casting type-conversion


【解决方案1】:

XYZ 的列表不是 X 的列表,即使 XYZ 从 X 继承或实现 X。Java 泛型不允许这样做。 更明确地说,将 XYZ 和 X 更改为真实对象(猫和动物),就像在 so link 中所说的那样

【讨论】:

  • 请将问题标记为重复问题,而不是简单地添加一个看到重复链接的答案
【解决方案2】:

假设您有 class ABC implements X,您可以将 ABC 的实例添加到 List&lt;X&gt;,但您不能将其添加到 ArrayList&lt;XYZ&gt;

仅仅因为ArrayList是由数组支持的,不要混淆2。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-08
    • 2017-02-26
    • 2015-06-24
    • 2011-12-09
    • 1970-01-01
    • 2017-05-25
    • 2011-11-15
    • 1970-01-01
    相关资源
    最近更新 更多