集合之使用迭代器(Iterator)遍历集合
使用for循环和while循环进行迭代遍历
自定义类:
public class TestTwo {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public TestTwo() {
}
public TestTwo(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "TestTwo [name=" + name + ", age=" + age + "]";
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if (obj instanceof TestTwo) {
TestTwo t=(TestTwo)obj;
if(this.name.equals(t.getName())&&this.age==t.getAge()) {
return true;
}
}
return false;
}
for循环:
public static void main(String[] args) {
//所有的All方法啊
Collection c1=new ArrayList();
c1.add(new TestTwo("Spring",12));
c1.add(new TestTwo("Summer",12));
c1.add(new TestTwo("Autumn",12));
c1.add(new TestTwo("Winter",12));
for(Iterator iter=c1.iterator();iter.hasNext();) {
TestTwo dt=(TestTwo)iter.next();
System.out.println(dt.getName()+dt.getAge());
}
}
while循环:
public static void main(String[] args) {
//所有的All方法啊
Collection c1=new ArrayList();
c1.add(new TestTwo("Spring",12));
c1.add(new TestTwo("Summer",12));
c1.add(new TestTwo("Autumn",12));
c1.add(new TestTwo("Winter",12));
Iterator iter=c1.iterator();
while(iter.hasNext()) {
TestTwo dt=(TestTwo)iter.next();
System.out.println(dt.getName()+dt.getAge());
}
}

浙公网安备 33010602011771号