一、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);
1、
public static void main(String[] args) {2、
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);
}
public static void main(String[] args) {tips:增强for只能用于取数据,在for循环内对循环元素的赋值不会影响其原值。要修改用传统方法。
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);
}
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]);
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。