package test_run;
import java.util.ArrayList;
import java.util.Iterator;
class Al_class
{
int x;
Al_class() {
x=0;
}
void increment(){
++x;
}
int get_value(){
return x;
}
ArrayList<Al_class> class_declare(){
//void class_declare(){
Al_class alc1 = new Al_class();
Al_class alc2 = new Al_class();
Al_class alc3 = new Al_class();
alc1.increment();
alc1.increment();
alc1.increment();
alc2.increment();
ArrayList al = new ArrayList();
al.add(alc1);
al.add(alc2);
al.add(alc3);
return al;
}
} ///:~
class Main
{
public static void main(String[] args) {
Al_class a = new Al_class();
ArrayList<Al_class> b;
b=a.class_declare();
a.class_declare();
System.out.print(" Arraylist size= "+ b.size());
for (Al_class c : b ){
System.out.print("\n" + c.get_value() + "\n");
}
b.remove(0);
System.out.print(" Arraylist size= "+ b.size());
Iterator it= b.iterator();
while (it.hasNext()) {
System.out.print("\n" + it.next());
// Al_class e=it.next();
// System.out.print("\n" + e.get_value());
}
}
}
如何使用迭代器调用对象函数get_value
?它不是作业,而是自学。
答案 0 :(得分:2)
您必须使用泛型,这意味着将Iterator
更改为Iterator<A1_class>
:
Iterator<A1_class> it= b.iterator();
while (it.hasNext()) {
Al_class e=it.next();
System.out.print("\n" + e);
System.out.print("\n" + e.get_value());
}
答案 1 :(得分:0)
你可以通过几种方式
明确投射
while (it.hasNext()) {
Object o = it.next();
if(o instanceof Al_class){
Al_class e=(Al_class)o;
System.out.print("\n" + e.get_value());
}
}
<强>泛型强>
Iterator<A1_class> it= b.iterator();
while (it.hasNext()) {
Al_class e=it.next();
System.out.print("\n" + e.get_value());
}
你真的不应该再进行明确的类型检查了,但是它仍然存在并且用例有限。