gpt4 book ai didi

java - 从 itr.next() 返回的对象中打印成员

转载 作者:行者123 更新时间:2023-12-01 19:03:24 25 4
gpt4 key购买 nike

以下代码存在编译问题。编译错误也附上。请提出相同的解决方案。

代码:

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: error: incompatible types

temp = itr.next(); ^

required: test

found: Object

最佳答案

有两种解决方案:

旧解决方案(Java 1.5 之前):

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);
}
}

通用解决方案(Java 1.5 及更高版本):

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);
}
}

关于java - 从 itr.next() 返回的对象中打印成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11294818/

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