Traversing a collection of generally set in two ways:
1. iterating:
1 Set<String> set = new HashSet<String>();
2 Iterator<String> it = set.iterator();
3 while (it.hasNext()) {
4 String str = it.next();
5 System.out.println(str);
6 }
This method uses an iterator, slightly cumbersome, in fact, consider using the second method:
2.For loop through:
1 for (String str : set) {
2 System.out.println(str);
3 }
Note: You can not make changes while operating at the time of the set assembled in traverse, such as delete, this will cause a crash.
If the advantage is also reflected in the generic set is stored in the Object
for loop through:
1 Set<Object> set = new HashSet<Object>(); 2 for循环遍历: 3 for (Object obj: set) { 4 if(obj instanceof Integer){ 5 int aa= (Integer)obj; 6 }else if(obj instanceof String){ 7 String aa = (String)obj; 8 } 9 ........ 10 }