[Java学习笔记]增强for循环和Map的两种读取方式

时间:2021-12-03 13:30:04

一、Iterator迭代器方法

1、keySet方法 

2、entrySet方法

二、增强for循环

1、keySet方法

2、entrySet方法

先看写法:

for(类型 循环元素名称 : 循环对象){

}

迭代器方法:

1、

public static void main(String[] args) {Map info = new LinkedHashMap<>();info.put("1", "张三");info.put("2", "李四");info.put("3", "王二麻子");Set set = info.keySet();Iterator iterator = set.iterator();while(iterator.hasNext()){String key = (String)iterator.next();String name = (String)info.get(key);System.out.println(key + "=" + name);}}
2、

Set set = info.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()){
Map.Entry entry = (java.util.Map.Entry) iterator.next();
String key = (String) entry.getKey();
String name = (String)entry.getValue();
System.out.println(key + "=" + name);

for循环方法

1、

public static void main(String[] args) {
Map info = new LinkedHashMap<>();
info.put("1", "张三");
info.put("2", "李四");
info.put("3", "王二麻子");
for (Object obj : info.keySet()){
String key = (String) obj;
String name = (String) info.get(key);
System.out.println(key + "=" + name);
}
2、

public static void main(String[] args) {
Map info = new LinkedHashMap<>();
info.put("1", "张三");
info.put("2", "李四");
info.put("3", "王二麻子");

for(Object obj:info.entrySet()){
Map.Entry entry = (java.util.Map.Entry) obj;
String key = (String) entry.getKey();
String name = (String) entry.getValue();
System.out.println(key + "=" + name);
}
tips:增强for只能用于取数据,在for循环内对循环元素的赋值不会影响其原值。要修改用传统方法。

e.g:

ArrayList<String> arr = new ArrayList<>();
arr.add("赵");
arr.add("钱");
arr.add("孙");
for (String i:arr ){
i = "李";
}
System.out.println(arr.get(0));
System.out.println(arr.get(1));
System.out.println(arr.get(2));
输出结果仍是赵钱孙。

传统方法:

int[] arr = {1,2,3};
for (int i = 0;i < arr.length;i++){
arr[i] = 10;
}
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);

输出10,10,10