遍历容器(List,Set,Map)
需要注意的是Set是无序不可重复的,也就意味着Set不可以使用for循环运用索引遍历
Set的遍历可以用迭代器和增强for循环(foreach)
package 容器的遍历; import java.util.*; public class study_01 { public static void main(String[] args) { //iterateListSet(); ietratorMap(); } //遍历List,Set private static void iterateListSet(){ List<String> list=new ArrayList<>(); list.add("11"); list.add("22"); list.add("33"); //通过索引遍历 list //这个方式只能遍历list不能遍历Set因为Set没有索引 //可以用迭代器和增强for循环遍历、Set; for (int i = 0; i < list.size(); i++) { String temp= list.get(i); System.out.println(temp); } //通过增强for循环,本质还是通过索引遍历 //这个list和set都能遍历 for (String temp: list) { System.out.println(temp); } //使用Iterator对象(也就是迭代器)for()调用 //通过方法创建Iteator对象 for (Iterator<String> iterator=list.listIterator();iterator.hasNext();){ String temp=iterator.next();//获取对象 System.out.println(temp); } System.out.println("============================"); //while()调用 Iterator iterator=list.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } } //遍历Map private static void ietratorMap(){ Map<String,String> map=new HashMap<>(); map.put("one","一"); map.put("two","二"); map.put("three","三"); Set<String> keys=map.keySet();//让键对象存储到Set容器中 for (String temp:keys) { System.out.println(temp); } for (String temp:keys) { System.out.println(map.get(temp));//通过get方法用键得到value } for (String temp:keys) { System.out.println(temp+map.get(temp)); } //遍历值 Collection<String> values= map.values();//返回的是value值 for (String temp:values) { System.out.println(temp); } //使用EntrySet遍历key,value Set<Map.Entry<String,String>> entrySet=map.entrySet();//一个Entry对象里面就是一个键值对 for (Map.Entry e:entrySet) { System.out.println(e.getKey()+"=="+e.getValue()); } } }