set的三種遍歷
阿新 • • 發佈:2018-02-05
iterator pos obj .... hset ext println asn else if
對 set 的遍歷
1.叠代遍歷:
Set<String> set = new HashSet<String>();
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String str = it.next();
System.out.println(str);
}
2.for循環遍歷:
for (String str : set) {
System.out.println(str);
}
優點還體現在泛型 假如 set中存放的是Object
Set<Object> set = new HashSet<Object>();
for循環遍歷:
for (Object obj: set) {
if(obj instanceof Integer){
int aa= (Integer)obj;
}else if(obj instanceof String){
String aa = (String)obj
}
........
}
set的三種遍歷