写在前面:
hashSet底层其实是hashmap,所以有些遍历方式他们之前是有共同点的。把map转为set来遍历会更方便。
hashSet三种遍历方式
import java.util.HashSet;
import java.util.Iterator;
public class IteratorTest {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<Integer>();
set.add(7);
set.add(2);
set.add(4);
set.add(5);
//1.迭代器
Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next());
}
System.out.println("\n-------------------------");
//2.for循环
for (int i : set){
System.out.print(i);
}
System.out.println("\n-------------------------");
//3.数组
Object[] objects = set.toArray();
for (Object o :objects){
System.out.print((Integer)o);
}
}
}
===========运行结果=============
2457
-------------------------
2457
-------------------------
2457
hashMap四种遍历方式
import java.util.*;
public class IteratorTest {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1,"hello");
map.put(2,"you");
map.put(3,"world");
//1.keySet的迭代器
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()) {
Map.Entry<Integer, String> next = iterator.next();
System.out.print(next.getValue()+ " ");
}
System.out.println("\n------------------------------------");
// 2 .直接使用map.keySet
for(Integer i :map.keySet()){
System.out.print(map.get(i)+" ");
}
System.out.println("\n------------------------------------");
// 3.使用map的entrySet
Set<Map.Entry<Integer, String>> entries = map.entrySet();
for(Map.Entry<Integer, String> entry : entries){
System.out.print(entry.getValue() + " ");
}
System.out.println("\n------------------------------------");
//4. map的values遍历所有的value,(不能便利key):Collection values = map.values();
for(String string : map.values()){
System.out.print(string + " ");
}
}
}
运行结果
hello you world
------------------------------------
hello you world
------------------------------------
hello you world
------------------------------------
hello you world