1. 程式人生 > >set集合遍歷方法

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
             }
              ........

}