Java集合總結(jié)

Java 集合總結(jié)

Java集合類提供了一組接口用于存儲(chǔ)/操作一系列的元素。

繼承結(jié)構(gòu)

集合類繼承結(jié)構(gòu)

Collection

Collection是List以及Set的基類,代表了一組集合,定義了add remove等集合必須實(shí)現(xiàn)的接口。

方法 作用
Iterator<E> iterator() 返回一個(gè)Iterator用于遍歷集合
boolean add(E e) 添加一個(gè)元素用于,如果Collection發(fā)生了變化,返回true
boolean remove(Object o) 刪除一個(gè)元素,如果Collection發(fā)生變化,返回true
int size() 返回集合中元素的個(gè)數(shù)
boolean isEmpty() 如果集合為空則返回true

List

概述

List接口繼承自 Collection,在Collection的基礎(chǔ)上增加了隨機(jī)訪問的功能。其增加的方法如下:

方法 作用
E get(int index) 返回index位置的元素
E remove(int index) 刪除index位置的元素
void add(int index, E element) 將元素插入指定位置
boolean addAll(int index, Collection<? extends E> c) 將集合c插入某個(gè)位置

ArrayList

ArrayList內(nèi)部是以數(shù)組實(shí)現(xiàn)的有如下特點(diǎn):

  1. 使用 new ArrayList() 實(shí)例化時(shí)初始化的是一個(gè)空的數(shù)組
  2. 當(dāng)數(shù)組空間不夠的時(shí)候增加當(dāng)前數(shù)組大小一般的空間,并發(fā)生數(shù)據(jù)拷貝
  3. 隨機(jī)讀(get(index index))等接口取效率較高
  4. 指定位置增加,刪除等方法都需要移動(dòng)(拷貝)數(shù)組中的數(shù)據(jù),效率較低
  5. 非線程安全

LinkedList

LinkedList實(shí)際上是雙向鏈表,其鏈表節(jié)點(diǎn)的定義如下代碼:

private static class Node<E> {
    E item;
    Node<E> next;
    Node<E> prev;

    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}

其特點(diǎn)如下:

  1. 隨機(jī)訪問需要遍歷鏈表,效率較ArrayList低
  2. 在指定位置刪除/增加元素?zé)o需移動(dòng)元素,效率較ArrayList高

Vector

Vector內(nèi)部依然是以數(shù)組實(shí)現(xiàn),其中的方法都增加了synchronized關(guān)鍵字,可以堪稱線程安全版的ArrayList。

Set

Set可以看成不允許重復(fù)的對(duì)象集合。和List對(duì)比Set主要缺少了隨機(jī)訪問的一系接口,包括 get(int index), set(int index), sublist(int from,int to)等。

HashSet

HashSet 是一個(gè)常見的Set實(shí)現(xiàn),HashSet內(nèi)部通過一個(gè)HashMap來實(shí)現(xiàn),并將對(duì)象作為HashMap的Key存儲(chǔ),從而達(dá)到?jīng)]有重復(fù)元素的目的。

Map

Map提供了一種映鍵值對(duì)的機(jī)制,在map中,一個(gè)key只能返回一個(gè)Value,并且Key不允許有重復(fù)。

HashMap

  • HashMap 是以鍵值對(duì)鏈表數(shù)組來存儲(chǔ)元素的,其中鍵值對(duì)的基本數(shù)據(jù)結(jié)構(gòu)如下:
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
}

其中key 和 value代表鍵,HashMap通過鏈表來解決沖突,當(dāng)鏈表長(zhǎng)度較大時(shí)則會(huì)將鏈表轉(zhuǎn)換成樹以換取更高的效率。

  • HashMap中的Hash函數(shù)如下:
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

tab[(n - 1) & hash]

通過鏈表來解決沖突,當(dāng)鏈表長(zhǎng)度較大(超過64)時(shí)則會(huì)將鏈表轉(zhuǎn)換成樹以換取更高的效率。

  • HashMap默認(rèn)的Table大小為16,如果添加鍵值對(duì)后size超過一定的大小,則需要重新生成鍵值對(duì)的數(shù)組,并重建Hash表。

HashTable

HashTable 可以等價(jià)于HashMap,區(qū)別有如下幾點(diǎn):

  1. HashTable是線程安全的,HashMap不是
  2. HashTable不能接收null作為key,HashMap可以。

常見工具類

  • Arrays 包含了一系列操作數(shù)組的靜態(tài)方法,包括 sort, fill,binarySearch等。

  • Collections 包含了一系列操作Collecntion類的靜態(tài)方法,包括sort,fill,bianrySearch等

常見問題

如何遍歷Collection

  1. 使用Iterator
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    System.out.print(iterator.next());
}
  1. foreach循環(huán)
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
for (String str : list) {
    System.out.print(str);
}
  1. 轉(zhuǎn)換為數(shù)組
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
String[] strArray = new String[list.size()];
strArray = list.toArray(strArray);
for (int i = 0; i < strArray.length; i++) {
    System.out.print(strArray[i]);
}

如何遍歷Map

  1. 通過Key
Map<String, Integer> nameAgeMap = new HashMap<String, Integer>();
nameAgeMap.put("Tom", 1);
nameAgeMap.put("Jerry", 2);
nameAgeMap.put("Alen", 3);
Set<String> keySet = nameAgeMap.keySet();
for (String key : keySet) {
    System.out.print("(" + key + ", " + nameAgeMap.get(key) + ")\r\n");
}
  1. 通過Entry
Map<String, Integer> nameAgeMap = new HashMap<String, Integer>();
nameAgeMap.put("Tom", 1);
nameAgeMap.put("Jerry", 2);
nameAgeMap.put("Alen", 3);
Set<Entry<String, Integer>> entrySet = nameAgeMap.entrySet();
for (Entry<String, Integer> entry : entrySet) {
    System.out.print("(" + entry.getKey() + ", " + entry.getValue() + ")\r\n");
}
  1. 只遍歷Value
Map<String, Integer> nameAgeMap = new HashMap<String, Integer>();
nameAgeMap.put("Tom", 1);
nameAgeMap.put("Jerry", 2);
nameAgeMap.put("Alen", 3);
Collection<Integer> values = nameAgeMap.values();
for (int value : values) {
    System.out.print("(value  is " + value + ")\r\n");
}

LinkedList 和 ArrayList有什么不同

  • ArrayList 內(nèi)部以數(shù)組實(shí)現(xiàn),LinkedList是雙向鏈表
  • ArrayList 隨機(jī)訪問效率較高
  • LinkedList 在插入刪除時(shí)效率較高

HashSet 和 HashMap有什么不同

  • HashSet 是Set 代表個(gè)補(bǔ)充復(fù)的對(duì)象的集合
  • HashMao 是Mao,代表了一個(gè)鍵值對(duì)的集合
  • HashSet 內(nèi)部是通過HashTable實(shí)現(xiàn)的

HashMap 和 Hashtable有什么不同

  • Hashtable 線程安全,但是不能接受null作為key
  • HashMap 不是線程安全的,可以接受null作為Key

Iterator 和 Enumeration有什么不同

IteratorEnumeration都是Java中的接口,兩者的區(qū)別如下:

Iterator Enumeration
是否還有更多元素 hasNext hasMoreElements
返回下一個(gè)元素 next nextElement
刪除上一個(gè)獲得的元素 remove

Comparable 和 Comparator的區(qū)別

Comparable 接口中只定義如下,實(shí)現(xiàn)了Comparable的類可以和該類的其他對(duì)象進(jìn)行比較

public interface Comparable<T> {
    public int compareTo(T o);
}

Comparator 接口定義如下,實(shí)現(xiàn)了Comparator的類可以用于對(duì)比一個(gè)類的兩個(gè)實(shí)例。

public interface Comparator<T> {
    int compare(T o1, T o2);
}

通常有兩種情況需要使用到Comparator:

  1. 比較未實(shí)現(xiàn)Comparable類的實(shí)例
  2. 實(shí)現(xiàn)了Comparable的類的實(shí)現(xiàn)方式和不滿足需求

集合排序

以Person類為例,Person類實(shí)現(xiàn)了Comprable接口:

static class Person implements Comparable<Person> {
    String mName;
    int mAge;;

    public Person(String name, int age) {
        mName = name;
        mAge = age;
    }

    public int compareTo(Person otherPerson) {
        return mAge - otherPerson.mAge;
    }

    @Override
    public String toString() {
        return "[ " + mName + "," + mAge + " ]";
    }
}
  1. 默認(rèn)排序
    由于Person實(shí)現(xiàn)了Comparable接口,可以直接使用Collections.sort方法排序,代碼如下:
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Allen", 30));
personList.add(new Person("Bill", 28));
personList.add(new Person("Carl", 25));
Collections.sort(personList);
for (Person person : personList) {
    System.out.print(person + "\r\n");
}

輸出如下:

[ Carl,25 ]

[ Bill,28 ]

[ Allen,30 ]

  1. 通過Comparator 自定義排序方式,代碼如下:
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Allen", 30));
personList.add(new Person("Bill", 28));
personList.add(new Person("Carl", 25));
personList.sort(new Comparator<Person>() {

    public int compare(Person arg0, Person arg1) {
        return arg0.mName.compareTo(arg1.mName);
    }
});

for (Person person : personList) {
    System.out.print(person + "\r\n");
}

[ Allen,30 ]

[ Bill,28 ]

[ Carl,25 ]

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • java筆記第一天 == 和 equals ==比較的比較的是兩個(gè)變量的值是否相等,對(duì)于引用型變量表示的是兩個(gè)變量...
    jmychou閱讀 1,645評(píng)論 0 3
  • 一、基本數(shù)據(jù)類型 注釋 單行注釋:// 區(qū)域注釋:/* */ 文檔注釋:/** */ 數(shù)值 對(duì)于byte類型而言...
    龍貓小爺閱讀 4,445評(píng)論 0 16
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,652評(píng)論 18 399
  • 從三月份找實(shí)習(xí)到現(xiàn)在,面了一些公司,掛了不少,但最終還是拿到小米、百度、阿里、京東、新浪、CVTE、樂視家的研發(fā)崗...
    時(shí)芥藍(lán)閱讀 42,791評(píng)論 11 349
  • 每首歌在不同時(shí)期經(jīng)歷的我們都有特殊的意義。2015年的11月對(duì)我有極其特殊的意義。那個(gè)有點(diǎn)冷的11月,我處了四年的...
    曾曾的麻麻閱讀 239評(píng)論 0 0

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