List
List<String> list = new ArrayList<>();
list.add("张三");
list.add("李四");
list.add("王五");
//遍历List
//方式一:for循环
System.out.print("for循环遍历List:");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i));
}
System.out.println();
//方式二:增强型for循环
System.out.print("增强型for循环遍历List:");
for (String str :
list) {
System.out.print(str);
}
System.out.println();
//方式三:Iterator迭代器方式遍历
//for循环方式
System.out.print("Iterator迭代器遍历List(for循环):");
for (Iterator<String> iterator = list.iterator();iterator.hasNext();){
System.out.print(iterator.next());
}
System.out.println();
//while循环方式
System.out.print("Iterator迭代器遍历List(while循环):");
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next());
iterator.remove(); //如果想一边遍历一边删除,建议使用此种方式
}
Set
Set<String> set = new HashSet<>();
set.add("one");
set.add("two");
set.add("three");
set.add("four");
//遍历Set
//方式一:增强型for循环(底层用HashMap实现不能用简单for循环)
System.out.print("增强型for循环遍历Set:");
for (String str :
set) {
System.out.print(str);
}
System.out.println();
//方式二:迭代器Iterator
System.out.print("Iterator迭代器遍历Set:");
for (Iterator<String> iteraotr = set.iterator();iteraotr.hasNext();){
System.out.print(iteraotr.next());
} //while循环一样
Map
//遍历Map
Map<Integer,String> map = new HashMap<>();
map.put(1,"张三");
map.put(2,"李四");
map.put(3,"王五");
map.put(4,"赵六");
System.out.println();
//通过keySet方式
System.out.print("keySet方法遍历Map:");
Set<Integer> tmp = map.keySet();
for (Iterator<Integer> iterator1 = tmp.iterator();iterator1.hasNext();){
Integer key = iterator1.next();
System.out.print(key+"-->"+map.get(key));
}
System.out.println();
//通过entrySet方式
System.out.print("entrySet方法遍历Map:");
Set<Map.Entry<Integer,String>> t = map.entrySet();
for (Iterator<Map.Entry<Integer,String>> iterator1 = t.iterator();iterator1.hasNext();){
Map.Entry<Integer,String> entry = iterator1.next();
System.out.print(entry.getKey()+"-->"+entry.getValue());
}