Java Collections總結

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) {  
        //存放學生類的動態(tài)數(shù)組的初始化  
        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);  
        //初始化之后先打印以下這個動態(tài)數(shù)組  
        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接口的重寫  
        //這個接口就一個抽象函數(shù),給出的參數(shù)與返回值都是定死的。  
        Collections.sort(studentArr, new Comparator<Object>() {  
            public int compare(Object o1, Object o2) {  
                //你首先設置你要比較的東西  
                //具體是把參數(shù)中的Object強制轉換成你要比較的東西,這里是兩個Student類  
                //這里的s1,s2與上面的s1,s2一點關系都沒有,只是抽象的前者與后者的關系  
                Student s1 = (Student) o1;  
                Student s2 = (Student) o2;  
                //如果前者的學號大于后者的學號,就是前者大于后者,返回1系統(tǒng)就會識別是前者大于后者  
                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);  
        }  
    }  
}
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容