容器【双例集合、TreeMap容器的使用、 Iterator接口、Collections工具类】(四)-全面详解(学习总结---从入门到深化)(中):https://developer.aliyun.com/article/1419934
元素自身实现比较规则
public class Users implements Comparable<Users>{ private String username; private int userage; public Users(String username, int userage) { this.username = username; this.userage = userage; } public Users() { } @Override public boolean equals(Object o) { System.out.println("equals..."); if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Users users = (Users) o; if (userage != users.userage) return false; return username != null ? username.equals(users.username) : users.username == null; } @Override public int hashCode() { int result = username != null ? username.hashCode() : 0; result = 31 * result + userage; return result; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getUserage() { return userage; } public void setUserage(int userage) { this.userage = userage; } @Override public String toString() { return "Users{" + "username='" + username + '\'' + ", userage=" + userage + '}'; } //定义比较规则 //正数:大,负数:小,0:相等 @Override public int compareTo(Users o) { if(this.userage < o.getUserage()){ return 1; } if(this.userage == o.getUserage()){ return this.username.compareTo(o.getUsername()); } return -1; } }
public class TreeMapTest { public static void main(String[] args) { //实例化TreeMap Map<Users,String> map = new TreeMap<>(); Users u1 = new Users("oldlu",18); Users u2 = new Users("admin",22); Users u3 = new Users("sxt",22); map.put(u1,"oldlu"); map.put(u2,"admin"); map.put(u3,"sxt"); Set<Users> keys = map.keySet(); for(Users key :keys){ System.out.println(key+" --------- "+map.get(key)); } } }
通过比较器实现比较规则
public class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public Student() { } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + 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; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; if (age != student.age) return false; return name != null ? name.equals(student.name) : student.name == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + age; return result; } }
public class StudentComparator implements Comparator<Student> { //定义比较规则 @Override public int compare(Student o1, Student o2) { if(o1.getAge() > o2.getAge()){ return 1; } if(o1.getAge() == o2.getAge()){ return o1.getName().compareTo(o2.getName()); } return -1; } }
public class TreeMapTest { public static void main(String[] args) { Map<Student,String> treeMap = new TreeMap<>(new StudentComparator()); Student s1 = new Student("oldlu",18); Student s2 = new Student("admin",22); Student s3 = new Student("sxt",22); treeMap.put(s1,"oldlu"); treeMap.put(s2,"admin"); treeMap.put(s3,"sxt"); Set<Student> keys1 = treeMap.keySet(); for(Student key :keys1){ System.out.println(key+" ----"+treeMap.get(key)); } } }
TreeMap的底层源码分析
TreeMap是红黑二叉树的典型实现。我们打开TreeMap的源码,发 现里面有一行核心代码:
private transient Entry<K,V> root = null;
root用来存储整个树的根节点。我们继续跟踪Entry(是TreeMap的 内部类)的代码:
可以看到里面存储了本身数据、左节点、右节点、父节点、以及节 点颜色。 TreeMap的put()/remove()方法大量使用了红黑树的理 论。在本节课中,不再展开。需要了解更深入的,可以参考专门的 数据结构书籍。 TreeMap和HashMap实现了同样的接口Map,因此,用法对于调 用者来说没有区别。HashMap效率高于TreeMap;在需要排序的 Map时才选用TreeMap。
Iterator接口
Iterator迭代器接口介绍
Collection接口继承了Iterable接口,在该接口中包含一个名为 iterator的抽象方法,所有实现了Collection接口的容器类对该方法 做了具体实现。iterator方法会返回一个Iterator接口类型的迭代器 对象,在该对象中包含了三个方法用于实现对单例容器的迭代处 理。
Iterator对象的工作原理
Iterator接口定义了如下方法:
1 boolean hasNext(); //判断游标当前位置的下一个位置是否还有元素没有被遍历;
2 Object next(); //返回游标当前位置的下一个元素并将游标移动到下一个位置;
3 void remove(); //删除游标当前位置的元素,在执行完next后该操作只能执行一次;
Iterator迭代器的使用
迭代List接口类型容器
public class IteratorListTest { public static void main(String[] args) { //实例化容器 List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); //获取元素 //获取迭代器对象 Iterator<String> iterator = list.iterator(); //方式一:在迭代器中,通过while循环获取元素 while(iterator.hasNext()){ String value = iterator.next(); System.out.println(value); } System.out.println("-------------------------------"); //方法二:在迭代器中,通过for循环获取元素 for(Iterator<String> it = list.iterator();it.hasNext();){ String value = it.next(); System.out.println(value); } } }
迭代Set接口类型容器
public class IteratorSetTest { public static void main(String[] args) { //实例化Set类型的容器 Set<String> set = new HashSet<>(); set.add("a"); set.add("b"); set.add("c"); //方式一:通过while循环 //获取迭代器对象 Iterator<String> iterator = set.iterator(); while(iterator.hasNext()){ String value = iterator.next(); System.out.println(value); } System.out.println("-------------------------"); //方式二:通过for循环 for(Iterator<String> it = set.iterator();it.hasNext();){ String value = it.next(); System.out.println(value); } } }
迭代Map接口类型容器
public class IteratorMapTest { public static void main(String[] args) { //实例化HashMap容器 Map<String, String> map = new HashMap<String, String>(); //添加元素 map.put("a", "A"); map.put("b", "B"); map.put("c", "C"); //遍历Map容器方式一 Set<String> keySet = map.keySet(); for (Iterator<String> it = keySet.iterator(); it.hasNext();){ String key = it.next(); String value = map.get(key); System.out.println(key+" ------------- "+value); } System.out.println("------------------------"); //遍历Map容器方式二 Set<Map.Entry<String, String>> entrySet = map.entrySet(); Iterator<Map.Entry<String, String>> iterator = entrySet.iterator(); while(iterator.hasNext()){ Map.Entry entry = iterator.next(); System.out.println(entry.getKey()+" ------------ "+ entry.getValue()); } } }
在迭代器中删除元素
public class IteratorRemoveTest { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); Iterator<String> iterator = list.iterator(); while(iterator.hasNext()){ //不要在一次循环中多次调用next方法。 String value = iterator.next(); iterator.remove(); } System.out.println("----------------"); for(Iterator<String> it = list.iterator(); it.hasNext();){ System.out.println(it.next()); list.add("dddd"); } } }
遍历集合的方法总结
遍历List方法一:普通for循环
for(int i=0;i<list.size();i++){//list为集合的对象名 String temp = (String)list.get(i); System.out.println(temp); }
遍历List方法二:增强for循环(使用泛型!)
for (String temp : list) { System.out.println(temp); }
遍历List方法三:使用Iterator迭代器(1)
for(Iterator iter= list.iterator();iter.hasNext();){ String temp = (String)iter.next(); System.out.println(temp); }
遍历List方法四:使用Iterator迭代器(2)
Iterator iter =list.iterator(); while(iter.hasNext()){ Object obj = iter.next(); iter.remove();//如果要遍历时,删除集合中的元素,建议使用这种方式! System.out.println(obj); }
遍历Set方法一:增强for循环
for(String temp:set){ System.out.println(temp); }
遍历Set方法二:使用Iterator迭代器
for(Iterator iter = set.iterator();iter.hasNext();){ String temp = (String)iter.next(); System.out.println(temp); }
遍历Map方法一:根据key获取value
Map<Integer, Man> maps = new HashMap<Integer, Man>(); Set<Integer> keySet = maps.keySet(); for(Integer id : keySet){ System.out.println(maps.get(id).name); }
遍历Map方法二:使用entrySet
Set<Map.Entry<Integer, Man>> ss = maps.entrySet(); for (Iterator<Map.Entry<Integer, Man>> iterator = ss.iterator(); iterator.hasNext();) { Map.Entry e = iterator.next(); System.out.println(e.getKey()+"-- "+e.getValue()); }
Collections工具类
类 java.util.Collections 提供了对Set、List、Map进行排序、填充、 查找元素的辅助方法。
Collections工具类的常用方法
public class CollectionsTest { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("c"); list.add("b"); list.add("a"); //对元素排序 Collections.sort(list); for(String str:list){ System.out.println(str); } System.out.println("-------------------"); List<Users> list2 = new ArrayList<>(); Users u = new Users("oldlu",18); Users u2 = new Users("sxt",22); Users u3 = new Users("admin",22); list2.add(u); list2.add(u2); list2.add(u3); //对元素排序 Collections.sort(list2); for(Users user:list2){ System.out.println(user); } System.out.println("-------------------"); List<Student> list3 = new ArrayList<>(); Student s = new Student("oldlu",18); Student s1 = new Student("sxt",20); Student s2 = new Student("admin",20); list3.add(s); list3.add(s1); list3.add(s2); Collections.sort(list3,new StudentComparator()); for(Student student:list3){ System.out.println(student); } System.out.println("-------------------"); List<String> list4 = new ArrayList<>(); list4.add("a"); list4.add("b"); list4.add("c"); list4.add("d"); //洗牌 Collections.shuffle(list4); for(String str:list4){ System.out.println(str); } } }