Java中遍歷Set集合的方法
阿新 • • 發佈:2018-11-03
對 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 } ........ }