对 <span style="background-color: rgb(153, 255, 153);">set</span> 的<span style="background-color: rgb(160, 255, 255);">遍历</span>
1.迭代<span style="background-color: rgb(160, 255, 255);">遍历</span>:
<span style="background-color: rgb(153, 255, 153);">Set</span><String> <span style="background-color: rgb(153, 255, 153);">set</span> = new HashSet<String>();
Iterator<String> it = <span style="background-color: rgb(153, 255, 153);">set</span>.iterator();
while (it.hasNext()) {
String str = it.next();
System.out.println(str);
}
2.for循环<span style="background-color: rgb(160, 255, 255);">遍历</span>:
for (String str : <span style="background-color: rgb(153, 255, 153);">set</span>) {
System.out.println(str);
}
优点还体现在泛型 假如 <span style="background-color: rgb(153, 255, 153);">set</span>中存放的是Object
<span style="background-color: rgb(153, 255, 153);">Set</span><Object> <span style="background-color: rgb(153, 255, 153);">set</span> = new HashSet<Object>();
for循环<span style="background-color: rgb(160, 255, 255);">遍历</span>:
for (Object obj: <span style="background-color: rgb(153, 255, 153);">set</span>) {
if(obj instanceof Integer){
int aa= (Integer)obj;
}else if(obj instanceof String){
String aa = (String)obj
}
........
}
set遍历
最新推荐文章于 2024-07-08 14:58:49 发布