對 Set 的遍歷方法:
注:Set沒有g(shù)et方法割笙,所以不能像List那樣,從0到size循環(huán)get值
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循環(huán)遍歷:
for (String str : set) {
System.out.println(str);
}
優(yōu)點還體現(xiàn)在泛型 假如 set中存放的是Object
Set<Object> set = new HashSet<Object>();
for循環(huán)遍歷:
for (Object obj: set) {
if(obj instanceof Integer){
int aa= (Integer)obj;
}else if(obj instanceof String){
String aa = (String)obj
}
........
}