Java 从LinkedList返回项时类型不匹配
我有一件A类物品:Java 从LinkedList返回项时类型不匹配,java,object,linked-list,Java,Object,Linked List,我有一件A类物品: public class A { private int num; private char color; } 我试图使用迭代器从LinkedList读入数组,如下所示: public static void main() { LinkedList<A> A = new LinkedList<A>(); //make some objects of class A A.add(A1); A.add(
public class A
{
private int num;
private char color;
}
我试图使用迭代器从LinkedList读入数组,如下所示:
public static void main()
{
LinkedList<A> A = new LinkedList<A>();
//make some objects of class A
A.add(A1);
A.add(A2);
A.add(A3);
Iterator it = A.iterator();
A[] arrayA = new A[3];
for (int i = 0; i < 3; i++)
{
> arrayA[i] = it.next();
}
}
publicstaticvoidmain()
{
LinkedList A=新建LinkedList();
//制作一些A类的对象
A.加入(A1);
A.加入(A2);
A.加入(A3);
迭代器it=A.Iterator();
A[]arrayA=新的A[3];
对于(int i=0;i<3;i++)
{
>arrayA[i]=it.next();
}
}
上面代码中标有
的行给出了以下编译器错误:类型不匹配:无法从对象转换为
我查了一下,认为通过将LinkedList实例化为A类型,可以避免原始类型的问题,LinkedList将返回A,而不是对象,但它仍然会给我相同的编译器错误。为什么会这样?您必须指定迭代器的泛型:
Iterator<T> it = A.iterator();
因为,it.next()代码>返回对象
实例,因为您尚未在下面的行中指定类型
Iterator it = A.iterator();
您需要指定泛型以返回A
的实例
Iterator<A> it = A.iterator();
Iterator it=A.Iterator();
因为您没有指定迭代器的类型,所以您的迭代器是原始类型的,请在此处更正代码:
public static void main() {
LinkedList<A> A = new LinkedList<A>();
A.add(new A());
A.add(new A());
A.add(new A());
Iterator<A> it = A.iterator();
A[] arrayA = new A[3];
for (int i = 0; i < 3; i++) {
arrayA[i] = it.next();
}
}
publicstaticvoidmain(){
LinkedList A=新建LinkedList();
A.添加(新的A());
A.添加(新的A());
A.添加(新的A());
迭代器it=A.Iterator();
A[]arrayA=新的A[3];
对于(int i=0;i<3;i++){
arrayA[i]=it.next();
}
}
第15行是哪一行?
public static void main() {
LinkedList<A> A = new LinkedList<A>();
A.add(new A());
A.add(new A());
A.add(new A());
Iterator<A> it = A.iterator();
A[] arrayA = new A[3];
for (int i = 0; i < 3; i++) {
arrayA[i] = it.next();
}
}