1.迭代遍历:
Set<String> set = new HashSet<String>(); //集合都可以用Iterator来遍历
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){ //若是Integer类型对象
int aa= (Integer)obj; //从包装类Integer 转为基本数据类型
}else if(obj instanceof String){ //若是String类型对象 转为String类型
String aa = (String)obj
}
........
}
Set<String> set = new HashSet<String>(); //集合都可以用Iterator来遍历
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){ //若是Integer类型对象
int aa= (Integer)obj; //从包装类Integer 转为基本数据类型
}else if(obj instanceof String){ //若是String类型对象 转为String类型
String aa = (String)obj
}
........
}