java中集合总结
//建立一个Student实体
package com.linshao;
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.linshao; import java.util.HashMap; import java.util.Iterator; import java.util.Map; //增强的for循环不能对容器进行修改操作 public class Test { public static void main(String[] args) { Student stu1 = new Student(); stu1.setAge(18); stu1.setName("james"); Student stu2 = new Student(); stu2.setAge(19); stu2.setName("kobe"); Student stu3 = new Student(); stu3.setAge(20); stu3.setName("kory"); Map<Integer, Student> map = new HashMap<Integer, Student>(); map.put(1, stu1); map.put(2, stu2); map.put(3, stu2); System.out.println("遍历方法一,通过Map.keySet遍历key和value"); for (Integer key : map.keySet()) { System.out.println("key= " + key + " and value= " + map.get(key)); } System.out.println("遍历方法二,通过Map.keySet遍历key和value"); for (Iterator<Map.Entry<Integer, Student>> iter = map.entrySet() .iterator(); iter.hasNext();) { Map.Entry<Integer, Student> entry = iter.next(); System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); } System.out.println("遍历方法三:通过Map.entrySet遍历key和value"); for (Map.Entry<Integer, Student> entry : map.entrySet()) { System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); } System.out.println("遍历方法四:通过Map.values()遍历所有的value,但不能遍历key"); for (Student v : map.values()) { System.out.println("value= " + v); } } }
增强for循环的问题
首先增强for循环和iterator遍历的效果是一样的,也就说增强for循环的内部也就是调用iteratoer实现的,
但是增强for循环有些缺点,例如不能在增强循环里动态的删除集合内容。就是说不能修改
ArrryList与LinkedList
当遍历ArrayList的时候用普通的for循环效率高一些
当遍历LinkedList的时候用Iterator迭代器效率高一些