[code]
尚学堂_马士兵_第七章_Iterator学习
[/code]
[code]
package com.iterator;
import java.util.Iterator ;
import java.util.Collection ;
import java.util.HashSet ;
public class TestIterator {
public static void main(String ages[]) {
Collection c = new HashSet() ;
c.add(new Name("f1","11")) ;
c.add(new Name("f2","22")) ;
c.add(new Name("f3","33")) ;
Iterator i = c.iterator() ;
while(i.hasNext()) {
//next 返回值是object 类型,需要转换成相应类型,此处也用到多态
Name name = (Name)i.next() ; //将游标移到下一个位置
System.out.println(name.getFirstName()) ;
}
// remove
c.add(new Name("f4","4444")) ;
c.add(new Name("f5","55")) ;
c.add(new Name("f6","666")) ;
for(Iterator j =c.iterator(); j.hasNext(); ) {
Name name = (Name)j.next() ;
if(name.getSecondName().length() < 3 )
j.remove();
//c.remove(name) ; //不能调用容器本身的remove方法,iterator 内部执行了锁定,就其内部可看
}
System.out.println(c) ;
}
}
class Name {
private String firstName ;
private String secondName ;
public Name(String firstName, String secondName) {
this.firstName = firstName ;
this.secondName = secondName ;
}
public String getFirstName() {
return firstName ;
}
public String getSecondName() {
return secondName ;
}
public String toString() {
return firstName + " " + secondName ;
}
}
[/code]
[code]
结果:
f2
f1
f3
[f6 666, f4 4444]
[/code]
[code]
HashSet无序,所以遍历出来的结果会不一样
[/code]
[img]/upload/attachment/97705/3f248c66-ba3f-39e4-94c0-146902b9a47e.bmp[/img]
尚学堂_马士兵_第七章_Iterator学习
[/code]
[code]
package com.iterator;
import java.util.Iterator ;
import java.util.Collection ;
import java.util.HashSet ;
public class TestIterator {
public static void main(String ages[]) {
Collection c = new HashSet() ;
c.add(new Name("f1","11")) ;
c.add(new Name("f2","22")) ;
c.add(new Name("f3","33")) ;
Iterator i = c.iterator() ;
while(i.hasNext()) {
//next 返回值是object 类型,需要转换成相应类型,此处也用到多态
Name name = (Name)i.next() ; //将游标移到下一个位置
System.out.println(name.getFirstName()) ;
}
// remove
c.add(new Name("f4","4444")) ;
c.add(new Name("f5","55")) ;
c.add(new Name("f6","666")) ;
for(Iterator j =c.iterator(); j.hasNext(); ) {
Name name = (Name)j.next() ;
if(name.getSecondName().length() < 3 )
j.remove();
//c.remove(name) ; //不能调用容器本身的remove方法,iterator 内部执行了锁定,就其内部可看
}
System.out.println(c) ;
}
}
class Name {
private String firstName ;
private String secondName ;
public Name(String firstName, String secondName) {
this.firstName = firstName ;
this.secondName = secondName ;
}
public String getFirstName() {
return firstName ;
}
public String getSecondName() {
return secondName ;
}
public String toString() {
return firstName + " " + secondName ;
}
}
[/code]
[code]
结果:
f2
f1
f3
[f6 666, f4 4444]
[/code]
[code]
HashSet无序,所以遍历出来的结果会不一样
[/code]
[img]/upload/attachment/97705/3f248c66-ba3f-39e4-94c0-146902b9a47e.bmp[/img]