以下代码包含编译问题。编译错误也附加了。请提出相同的解决方案。
代码:
import java.util.*;
class test{
int key;
public static void main(String []args){
test obj = new test();
obj.key = 9999;
LinkedList al = new LinkedList();
al.add(obj);
Iterator itr = al.iterator();
while(itr.hasNext()){
test temp = new test();
temp = itr.next();
System.out.println(temp.key);
}
}
}
编译错误:
test.java:17:错误:不兼容的类型
temp = itr.next(); ^
必需:测试
发现:对象
答案 0 :(得分:2)
its.next()
会返回Object
而不是Test
按如下方式进行
LinkedList<Test> al = new LinkedList<Test>();
al.add(obj);
Iterator<Test> itr = al.iterator();
所以编译器现在知道LinkedList
a1
只能容纳Test
个实例,因此在迭代时我们只会有Test
的实例
答案 1 :(得分:2)
有两种解决方案:
public static void main(String []args){
test obj = new test();
obj.key = 9999;
LinkedList al = new LinkedList();
al.add(obj);
Iterator itr = al.iterator();
while(itr.hasNext()){
test temp = new test();
// use type cast
temp = (test) itr.next();
System.out.println(temp.key);
}
}
public static void main(String []args){
test obj = new test();
obj.key = 9999;
LinkedList<test> al = new LinkedList<test>();
al.add(obj);
Iterator<test> itr = al.iterator();
while(itr.hasNext()){
test temp = new test();
// use Generic
temp = itr.next();
System.out.println(temp.key);
}
}