美文网首页
Java Collections总结

Java Collections总结

作者: bin_guo | 来源:发表于2018-08-06 13:21 被阅读0次

    Collections

    • List (inherited from Collection Interface)
      • ArrayList, Vector, LinkedList, Stack
    • Queue (inherited from Collection Interface)
      • LinkedList, PriorityQueue
    • Set (inherited from Collection Interface)
      • HashSet, LinkedHashSet, TreeSet
    • Stack (inherited from Collection Interface)
    • Map
      • HashMap, TreeMap, WeakHashMap, HashTable

    Schematic Diagram

    Collections Map

    Iterator

    • Iterator, a light collection for those collections which implements Collection Interface.
    • ListIterator, a light collection for those collections which implements List Interface, extends Iterator Interface, has more functions for traverse forward and backward with the ability to add, set, and remove an item.
    Iterator ListIterator
    hasNext() hasNext()
    next() next()
    hasPrevious()
    previous()
    nextIndex()
    previousIndex()
    add()
    set()
    remove() remove()

    ArrayList, Vector, LinkedList

    Commonality: dynamically increasing the count of elements

    Difference ArrayList Vector LinkedList
    Storage mode Single List Single List Double List
    Continuous storage space Yes, extend 1.5x/time Yes, extend 2x/time No
    Access element speed Fast Fast Slow
    Modify element(middle) speed Slow Slow Fast
    Thread security Unsafe Safe Unsafe
    Performance High Low High

    HashMap, HashTable, TreeMap, and WeakHashMap

    According to the hash code of the key to store the key-value pair, it will be easier to access the value by looking for the key.

    Difference HashMap HashTable
    Allow null key Yes, only one No
    Has contains() No, but it has containsKey() and containsValue() Yes
    Thread security No Yes
    Performance High Low
    Traversable interface Iterator Enumeration
    Hash array default, increase 16, (old * 2) 11, (old * 2 + 1)
    Directly using hashCode No Yes

    TreeMap, implemented SortMap so that using for sorted structure
    LinkedHashMap, stored by original input sequence
    WeakHashMap, once the key is no longer be referenced, then it will be recycled immediately, but in HashMap, until the key is removed from the map it is still existing

    What is synchronize? How to make the HashMap synchronized?
    At the same time, there is only one thread can modify the map, any thread which is working on the update operation needs to request the lock of the object, and the others need to wait for the lock unlock.
    Map map = Collections.synchronizedMap(new HashMap());

    Customized Object as the key stored in Map

    Insert a pair of key-value

    1. Locate the key
      key --- using hashCode() to calculate ---> hash value
      hash value --- search hash value in map ---> list of key (the head of addresses)
      list of key --- traverse all of the keys, and using equals() to exam the same ---> one key
    2. Override hashCode() and equals()
      for example:
    class Person {
        String id;
        String name;
        public Person(String id, String name) {
            this.id = id;
            this.name = name;
        }
        public String toString() {
            return "id = " + id + ", name = " + name;
        }
        public int hashCode() {
            return id.hashCode();
        }
        public boolean equals(Object obj) {
            Person person = (Person)obj;
            return person.id.equals(this.id);
        }
    }
    

    Collections.sort()

    Create new Comparator<Object>(), and override compare method

    import java.util.*;  
    //以下是学生类Student定义,有点类似C语言的结构体啊!^_^  
    class Student {  
        public int s_no;  
        public String s_name;  
        public int s_class;  
    }  
    
    public class compareTest {  
        public static void main(String[] args) {  
            //存放学生类的动态数组的初始化  
            ArrayList<Student> studentArr = new ArrayList<Student>();  
            Student s1 = new Student();  
            s1.s_no = 3;  
            s1.s_name = "a";  
            s1.s_class = 102;  
            studentArr.add(s1);  
            Student s2 = new Student();  
            s2.s_no = 2;  
            s2.s_name = "b";  
            s2.s_class = 101;  
            studentArr.add(s2);  
            Student s3 = new Student();  
            s3.s_no = 1;  
            s3.s_name = "c";  
            s3.s_class = 103;  
            studentArr.add(s3);  
            //初始化之后先打印以下这个动态数组  
            System.out.println("排序前:");  
            for (int i = 0; i < studentArr.size(); i++) {  
                System.out  
                        .println("我是" + studentArr.get(i).s_class + "班的"  
                                + studentArr.get(i).s_name + "学号是"  
                                + studentArr.get(i).s_no);  
            }  
            //对于Comparator接口的重写  
            //这个接口就一个抽象函数,给出的参数与返回值都是定死的。  
            Collections.sort(studentArr, new Comparator<Object>() {  
                public int compare(Object o1, Object o2) {  
                    //你首先设置你要比较的东西  
                    //具体是把参数中的Object强制转换成你要比较的东西,这里是两个Student类  
                    //这里的s1,s2与上面的s1,s2一点关系都没有,只是抽象的前者与后者的关系  
                    Student s1 = (Student) o1;  
                    Student s2 = (Student) o2;  
                    //如果前者的学号大于后者的学号,就是前者大于后者,返回1系统就会识别是前者大于后者  
                    if (s1.s_no > s2.s_no) {  
                        return 1;  
                    }  
                    //小于同理  
                    if (s1.s_no < s2.s_no) {  
                        return -1;  
                    }  
                    //如果返回0则认为前者与后者相等  
                    return 0;  
                }  
            });  
            //比较完毕再输出以学号排序之后的结果  
            System.out.println("按学号升序排序后:");  
            for (int i = 0; i < studentArr.size(); i++) {  
                System.out  
                        .println("我是" + studentArr.get(i).s_class + "班的"  
                                + studentArr.get(i).s_name + "学号是"  
                                + studentArr.get(i).s_no);  
            }  
            //以下是以班级排序的过程  
            Collections.sort(studentArr, new Comparator<Object>() {  
                public int compare(Object o1, Object o2) {  
                    Student s1 = (Student) o1;  
                    Student s2 = (Student) o2;  
                    if (s1.s_class > s2.s_class) {  
                        return 1;  
                    }  
                    if (s1.s_class < s2.s_class) {  
                        return -1;  
                    }  
                    return 0;  
                }  
            });  
            System.out.println("按班级升序排序后:");  
            for (int i = 0; i < studentArr.size(); i++) {  
                System.out  
                        .println("我是" + studentArr.get(i).s_class + "班的"  
                                + studentArr.get(i).s_name + "学号是"  
                                + studentArr.get(i).s_no);  
            }  
        }  
    }
    

    相关文章

      网友评论

          本文标题:Java Collections总结

          本文链接:https://www.haomeiwen.com/subject/hbrwvftx.html