欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

深入淺出講解Java集合之Collection接口

 更新時(shí)間:2021年09月13日 15:26:32   作者:威斯布魯克.猩猩  
這篇文章主要介紹了深入淺出講解Java集合之Collection接口,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

一、集合框架的概述

背景:一方面,面向?qū)ο笳Z(yǔ)言對(duì)事物的體現(xiàn)都是以對(duì)象的形式,為了方便對(duì)多個(gè)對(duì)象的操作,就要對(duì)對(duì)象進(jìn)行存儲(chǔ),另一方面,使用Array存儲(chǔ)對(duì)象方面具有一些弊端,而Java集合就像一種容器,可以動(dòng)態(tài)的把多個(gè)對(duì)象的引用放入容器中。
1.集合、數(shù)組都是對(duì)多個(gè)數(shù)據(jù)進(jìn)行存儲(chǔ)操作的結(jié)構(gòu),簡(jiǎn)稱Java容器。
說(shuō)明:此時(shí)的存儲(chǔ),主要指的是內(nèi)存層面的存儲(chǔ),不涉及到持久化的存儲(chǔ)(.txt,.jpg,.avi,數(shù)據(jù)庫(kù)中)
2. 數(shù)組在存儲(chǔ)多個(gè)數(shù)據(jù)方法的特點(diǎn):
> 一旦初始化以后,其長(zhǎng)度就確定了。
> 數(shù)組一旦定義好,其元素的類型也就確定了。我們也就只能操作指定類型的數(shù)據(jù)了。
比如:String[] arr;int[] arr1;Object[] arr2(多態(tài):數(shù)組中也可存放子類類型的數(shù)據(jù)(String等));
3. 數(shù)組在存儲(chǔ)多個(gè)數(shù)據(jù)方面的缺點(diǎn):
> 一旦初始化以后,其長(zhǎng)度就不可修改。
> 數(shù)組中提供的方法非常有限,對(duì)于添加、刪除、插入數(shù)組等操作,非常不便,同時(shí)效率不高
> 獲取數(shù)組中實(shí)際元素的個(gè)數(shù)的需求,數(shù)組沒(méi)有現(xiàn)成的屬性或方法可用
> 數(shù)組存儲(chǔ)數(shù)據(jù)的特點(diǎn):有序、可重復(fù)。對(duì)于無(wú)序、不可重復(fù)的需求,不能滿足

二、集合框架(Java集合可分為Collection 和 Map 兩種體系)

A. Collection接口:?jiǎn)瘟屑?,用?lái)存儲(chǔ)一個(gè)一個(gè)的對(duì)象
a.List接口:存儲(chǔ)有序的、可重復(fù)的數(shù)據(jù)。--->"動(dòng)態(tài)"數(shù)組
|---ArrayList、LinkedList、Vector
b.Set接口:存儲(chǔ)無(wú)序的、不可重復(fù)的數(shù)據(jù) --->高中講的"集合"
|---HashSet、LinkedHashSet、TreeSet
B. Map接口:雙列集合,用來(lái)存儲(chǔ)一對(duì)(key - value)一對(duì)的數(shù)據(jù) --->高中函數(shù):y = f(x)
|---HashMap、LinkedHashMap、TreeMap、Hashable、Properties

三、Collection接口中的方法的使用

public void test1(){
        Collection coll = new ArrayList();
        //add(Object e):將元素e添加到集合coll中
        coll.add("AA");
        coll.add("BB");
        coll.add(123);//自動(dòng)裝箱
        coll.add(new Date());
        //size():獲取添加的元素的個(gè)數(shù)
        System.out.println(coll.size());//4
        //addAll(Collection coll1):將coll1集合中的元素添加到當(dāng)前的集合中
        Collection coll1 = new ArrayList();
        coll1.add(456);
        coll1.add("CC");
        coll.addAll(coll1);
        System.out.println(coll.size());//6
        System.out.println(coll);
        //clear():清空集合元素(對(duì)象還在,只是元素沒(méi)了)
        coll.clear();
        //isEmpty():判斷當(dāng)前集合是否為空
        System.out.println(coll.isEmpty());
    }
 //結(jié)論:向Collection接口的實(shí)現(xiàn)類的對(duì)象中添加數(shù)據(jù)obj時(shí),要求obj所在類要重寫equals().
    public void test2(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);
        //1.contains(Object obj):判斷當(dāng)前集合中是否包含obj
        //我們?cè)谂袛鄷r(shí)會(huì)調(diào)用obj對(duì)象所在類的equals()
        boolean contains = coll.contains(123);
        System.out.println(contains);
        System.out.println(coll.contains(new String("Tom")));//true
        System.out.println(coll.contains(new Person("Jerry",20)));//false-->ture
        //2.containsAll(Collection coll1):判斷形參coll1中的所有元素是否都存在于當(dāng)前集合中
        Collection coll1 = Arrays.asList(123,456);
        System.out.println(coll.containsAll(coll1));
    }

public void test3(){
        //3.remove(Object obj):從當(dāng)前集合中移除obj元素
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);
        coll.remove(1234);
        System.out.println(coll);//[123, 456, Person{name='Jerry', age=20}, Tom, false]
        coll.remove(new Person("Jerry",20));
        System.out.println(coll);//[123, 456, Tom, false]
        //4.removeAll(Collection coll1)://從當(dāng)前集合中移除coll1中所有的元素
        Collection coll1 = Arrays.asList(123,4567);
        coll.removeAll(coll1);
        System.out.println(coll);//[456, Tom, false]
}
 public void test4(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);
        //5.retainAll(Collection coll1):獲取帶那個(gè)前集合和coll1集合的交集,并返回給當(dāng)前集合
//        Collection coll1 = Arrays.asList(123.456,789);
//        coll.retainAll(coll1);
//        System.out.println(coll);
        //6.equals(Object obj):要想返回true,需要當(dāng)前集合和形參集合的元素都相同
        Collection coll1 = new ArrayList();
        coll1.add(123);
        coll1.add(456);
        coll1.add(new Person("Jerry",20));
        coll1.add(new String("Tom"));
        coll1.add(false);
        System.out.println(coll.equals(coll1));//true
 }
 public void test5(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);
        //7.hashCode():返回當(dāng)前對(duì)象的哈希值
        System.out.println(coll.hashCode());
        //8.集合 --> 數(shù)組:toArray()
        Object[] arr = coll.toArray();
        for(int i = 0;i < arr.length;i++){
            System.out.println(arr[i]);
        }
        //拓展:數(shù)組 --> 集合:調(diào)用Arrays類的靜態(tài)方法asList()
        List<String> list = Arrays.asList(new String[]{"AA", "BB", "CC"});
        System.out.println(list);
        List arr1 = Arrays.asList(new int[]{123, 456});
        System.out.println(arr1.size());//1
        List arr2 = Arrays.asList(new Integer[]{123, 456});
        System.out.println(arr2.size());//2
 }

四、集合元素的遍歷操作

A. 使用(迭代器)Iterator接口

1.內(nèi)部的方法:hasNext() 和 next()
2.集合對(duì)象每次調(diào)用iterator()方法都得到一個(gè)全新的迭代器對(duì)象,默認(rèn)游標(biāo)都在集合的第一個(gè)元素 之前。
3.內(nèi)部定義了remove().可以在遍歷的時(shí)候,刪除集合中的元素,此方法不同于集合直接調(diào)用 remove()

注意:在調(diào)用it.next()方法之前必須要調(diào)用it.hasNext()進(jìn)行檢測(cè),若不調(diào)用,且下一條記錄無(wú)效,直接調(diào)用it.next()會(huì)拋出NoSuchEiementException異常。

public class IteratorTest {
    @Test
    public void test1(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);
        Iterator iterator = coll.iterator();
        //方式一:不推薦
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
        //報(bào)異常:NoSuchElementException
//        System.out.println(iterator.next());
        //方式二:不推薦
//        for(int i = 0;i < coll.size();i++){
//            System.out.println(iterator.next());
//        }
        //方式三:推薦
        //hasNext():判斷是否還有下一個(gè)元素
        while (iterator.hasNext()){
            //next():A 指針下移 B 將下移以后集合位置上的元素返回
            System.out.println(iterator.next());
        }
    }
    @Test
    public void test2(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);
        //錯(cuò)誤方式一:
//        Iterator iterator = coll.iterator();
//        while((iterator.next()) != null){
//            System.out.println(iterator.next());//456 Tom//跳著輸出
//        }//還會(huì)報(bào)異常:NoSuchElementException
        //錯(cuò)誤方式二:
        //集合對(duì)象每次調(diào)用iterator()方法都得到一個(gè)全新的迭代器對(duì)象,默認(rèn)游標(biāo)都在集合的第一個(gè)元素之前。
//        while(coll.iterator().hasNext()){
//            System.out.println(coll.iterator().next());//123死循環(huán)
//        }
    }
    //測(cè)試Iterator中的remove()
    @Test
    public void test3(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);
        //刪除集合中的"Tom"
        Iterator iterator = coll.iterator();
        while(iterator.hasNext()){
            Object obj = iterator.next();
            if("Tom".equals(obj)){
                iterator.remove();
            }
        }
        //遍歷集合
        iterator = coll.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

B. jdk5.0新增foreach循環(huán),用于遍歷集合、數(shù)組

 @Test//訪問(wèn)Collection
    public void test1(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);
        //for(集合元素的類型 局部變量:集合對(duì)象)
        //內(nèi)部仍然調(diào)用了迭代器
        for(Object obj : coll){
            System.out.println(obj);
        }
    }
    @Test//訪問(wèn)數(shù)組
    public void test2(){
        int[] arr = new int[]{1,3,4,5,6};
        //for(數(shù)組元素的類型 局部變量:數(shù)組對(duì)象)
        for(int i : arr){
            System.out.println(i);
        }
    }

一道筆試題

//筆試題
    @Test
    public void test3(){
        String[] arr = new String[]{"MM","MM","MM"};
        //方式一:普通for賦值//輸出:GG//拿著數(shù)組修改,數(shù)組存儲(chǔ)在堆中,可修改
//        for(int i = 0;i < arr.length;i++){
//            arr[i] = "GG";
//        }
        //方式二:增強(qiáng)for循環(huán)//輸出:MM//將數(shù)組中的元素一個(gè)個(gè)賦給字符型變量s,而s存儲(chǔ)在常量區(qū),不可被修改
        for(String s : arr){
            s = "GG";
        }
        for(int i = 0;i < arr.length;i++){
            System.out.println(arr[i]);
        }
    }

五、Collection子接口之一:List接口

簡(jiǎn)介:鑒于Java中數(shù)組用來(lái)存儲(chǔ)數(shù)據(jù)的局限性,我們通過(guò)使用List代替數(shù)組

List集合類中元素有序、且可重復(fù),集合中的每個(gè)元素都有其對(duì)應(yīng)的順序索引。

List容器中的元素都對(duì)應(yīng)一個(gè)整型的序號(hào)記載其在容器中的位置,可以根據(jù)序號(hào)存取容器中的元素。

List接口方法

 public void test1(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add("AA");
        list.add(new Person("Jerry",20));
        list.add(456);
        System.out.println(list);//[123, 456, AA, Person{name='Jerry', age=20}, 456]
 
        //void add(int index,Object ele):在index位置插入ele元素
        list.add(1,"BB");
        System.out.println(list);//[123, BB, 456, AA, Person{name='Jerry', age=20}, 456]
 
        //boolean addAll(int index,Collection eles):從index位置上開(kāi)始將eles中的所有元素添加進(jìn)來(lái)
        List list1 = Arrays.asList(1,2,3);
        list.addAll(list1);
        System.out.println(list.size());//9
 
        //Object get(int index):獲取指定index位置的元素
        System.out.println(list.get(0));//123
 }
 public void test2(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add("AA");
        list.add(new Person("Jerry",20));
        list.add(456);
 
        //int indexOf(Object obj):返回obj在集合中首次出現(xiàn)的位置,如果不存在,返回-1
        int index = list.indexOf(4567);
        System.out.println(index);//-1
 
        //int LastIndexOf(Object obj):返回obj在當(dāng)前集合中末次出現(xiàn)的位置
        System.out.println(list.lastIndexOf(456));//4
 
        //Object remove(int index):移除指定index位置的元素,并返回此元素
        Object obj = list.remove(0);//123
        System.out.println(list);//[456, AA, Person{name='Jerry', age=20}, 456]
 
        //Object set(int index,Object ele):設(shè)置指定index位置的元素為ele
        list.set(1,"CC");//[456, CC, Person{name='Jerry', age=20}, 456]
        System.out.println(list);
        //
        //List subList(int formIndex,int toIndex):返回從formIndex到toIndex位置的左閉右開(kāi)的子集合
        List subList = list.subList(2,4);
        System.out.println(subList);//[Person{name='Jerry', age=20}, 456]
        System.out.println(list);//[456, AA, Person{name='Jerry', age=20}, 456]
 }

遍歷List的方式

   public void test3(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add("AA");
        //方式一:Iterator迭代器的方式
        Iterator iterator = list.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //方式二:增強(qiáng)for循環(huán)
        for(Object obj : list){
            System.out.println(obj);
        }
        //方式三:普通for循環(huán)
        for(int i = 0;i < list.size();i++){
            System.out.println(list.get(i));
   }

區(qū)分List中remove(int index)和remove(Object obj)

 @Test
    public void test4(){
        ArrayList list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        updateList(list);
        System.out.println(list);
    }
    public static void updateList(List list){
        list.remove(2);//[1, 2]//刪掉角標(biāo)為2的元素
        list.remove(new Integer(2));//刪掉字符2
    }

面試題:ArrayList、LinkedList、Vector三者的異同?
同:三個(gè)類都是實(shí)現(xiàn)了List接口,存儲(chǔ)數(shù)據(jù)的特點(diǎn)相同:存儲(chǔ)有序的、可重復(fù)的數(shù)據(jù)
不同: |---ArrayList:作為L(zhǎng)ist接口的主要實(shí)現(xiàn)類:線程不安全的,效率高;底層使用Object[] elementData存儲(chǔ)
|---LinkedList:對(duì)于頻繁的插入、刪除操作,使用此類效率比ArrayList高;底層使用雙向鏈表存 儲(chǔ)
|---Vector:作為L(zhǎng)ist接口的古老的實(shí)現(xiàn)類;線程安全的,效率低;底層使用Object[] elementData存儲(chǔ)

ArrayList的源碼分析:

JDK 7情況下:

ArrayList list = new ArrayList();//底層創(chuàng)建了長(zhǎng)度是10的Object[]數(shù)組elementData
list.add(123);//elementData[0] = new Integer(123);
...
List.add(11);//如果此次的添加導(dǎo)致底層elementData數(shù)組容量不夠,則擴(kuò)容。
默認(rèn)情況下,擴(kuò)容為原來(lái)的容量的1.5倍,同時(shí)需要將原有的數(shù)組中的數(shù)據(jù)復(fù)制到新的數(shù)組中。
結(jié)論:建議開(kāi)發(fā)中使用帶參的構(gòu)造器:ArrayList list = new ArrayList(int capacity)

JDK 8中ArrayList的變化:

ArrayList list = new ArrayList();//底層Object[] elementData初始化為{}.并沒(méi)有創(chuàng)建長(zhǎng)度為10的數(shù)組
list.add(123);//第一次使用add()時(shí),底層才創(chuàng)建了長(zhǎng)度為10的數(shù)組,并將數(shù)據(jù)123添加到elementData[0]
后續(xù)的添加和擴(kuò)容操作與JDK 7相同

小結(jié):jdk7中的ArrayList的對(duì)象的創(chuàng)建類似于單例的餓漢式,而jdk8中的ArrayList的對(duì)象的創(chuàng)建類似于單例的懶漢式,延遲了數(shù)組的創(chuàng)建,節(jié)省內(nèi)存

LinkedList的源碼分析:

LinkedList list = new LinkedList();內(nèi)部沒(méi)有聲明數(shù)組,而是聲明了Node類型的first和last屬性,默認(rèn)值為null
list.add(123);//將123封裝到Node中,創(chuàng)建了Node對(duì)象。

其中,Node定義為:體現(xiàn)了LinkedList的雙向鏈表的說(shuō)法

private static class Node<E>{
     E item;
     Node<E> next;//變量記錄下一個(gè)元素的位置
     Node<E> prev;//變量記錄前一個(gè)元素的位置
     Node(Node<E> prev,E element,Node<E> next){
        this.item = element;
        this.next = next;
        this.prev = prev;    
     }
}

Vector的源碼分析:

jdk7和jdk8中通過(guò)Vector()構(gòu)造器創(chuàng)建對(duì)象時(shí),底層都創(chuàng)建了長(zhǎng)度為10的數(shù)組在擴(kuò)容方面,默認(rèn)擴(kuò)容為原來(lái)的數(shù)組長(zhǎng)度的2倍。

六、Collection子接口之一:Set接口

一、Set接口概述

> Set接口是Collection的子接口,set接口沒(méi)有提供額外的方法

> Set集合不允許包含相同的元素,如果試把兩個(gè)相同的元素加入同一個(gè)Set集合中,則添加操作失敗。

> Set判斷兩個(gè)對(duì)象是否相同不是使用 == 運(yùn)算符,而是根據(jù) equals() 方法

> 注意點(diǎn):

1.Set接口中沒(méi)有額外定義新的方法,使用的都是Collection中聲明過(guò)的方法。
2.要求:向Set中添加的數(shù)據(jù),其所在的類一定要重寫hashCode()和equals()
要求:重寫的hashCode()和equals()盡可能保持一致性:相等的對(duì)象必須是具有相等的數(shù)列碼
重寫兩個(gè)方法的小技巧:對(duì)象中用作equals()方法比較的Field,都應(yīng)該用來(lái)計(jì)算hashCode值

二、set接口的框架:

Collection接口:?jiǎn)瘟屑?,用?lái)存儲(chǔ)一個(gè)一個(gè)的對(duì)象
> Set接口:存儲(chǔ)無(wú)序的、不可重復(fù)的數(shù)據(jù) --->高中講的"集合"
A.HashSet:作為Set接口的主要實(shí)現(xiàn)類:線程不安全的,可以存儲(chǔ)null值
B.LinkedHashSet:作為HashSet的子類:遍歷其內(nèi)部數(shù)據(jù)時(shí),可以按照添加的順序遍歷
對(duì)于頻繁的遍歷操作,LinkedHashSet效率高于HashSet
C.TreeSet:可以按照添加對(duì)象的指定屬性,進(jìn)行排序

三、Set的三個(gè)實(shí)現(xiàn)類

重寫hashCode()方法的基本原則

> 在程序運(yùn)行時(shí),同一個(gè)對(duì)象多次調(diào)用hashCode()方法應(yīng)該返回相同的值。

> 當(dāng)兩個(gè)對(duì)象的equals()方法比較返回true時(shí),這兩個(gè)對(duì)象的hashCode()方法的返回值也應(yīng)相等

> 對(duì)象中用作equals()方法比較的Field,都應(yīng)該用來(lái)計(jì)算hashCode值。

public void test1(){
        HashSet set = new HashSet();
        set.add(456);
        set.add(123);
        set.add(123);
        set.add("AA");
        set.add("CC");
        set.add(new User("Tom",12));
        set.add(new User("Tom",12));
        set.add(129);
        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
//            AA
//            CC
//            129
//            456
//            123
//            User{name='Tom', age=12}
}

Set:存儲(chǔ)無(wú)序的、不可重復(fù)的數(shù)據(jù)

以HashSet為例說(shuō)明:
1.無(wú)序性:不等于隨機(jī)性。存儲(chǔ)的數(shù)據(jù)在底層數(shù)組中并非按照數(shù)組索引的順序添加,而是根據(jù)數(shù)據(jù)的哈希值決定的
2.不可重復(fù)性:保證添加的元素按照equals()判斷時(shí),不能返回true.即:相同的元素只添加一個(gè)
二、添加元素的過(guò)程:以HashSet為例:
我們向HashSet中添加元素a,首先調(diào)用元素a所在類的hashCode()方法,計(jì)算元素a的哈希值,此哈希值接著通過(guò)
某種算法計(jì)算出在HashSet底層數(shù)組中的存放位置(即為:索引位置),判斷此位置上是否已經(jīng)有元素:
如果此位置上沒(méi)有其他元素,則元素a添加成功。--->情況1
如果此位置上有其他元素b(或以鏈表形式存在的多個(gè)元素),則比較元素a與元素b的has值。
如果hash值不相同,則元素a添加成功。---->情況2
如果hash值相同,進(jìn)而需要調(diào)用元素a所在類的equals()方法:
equals()返回true,元素a添加失敗
equals()返回false,則元素a添加成功。----情況3
對(duì)于添加成功的情況2和情況3而言:元素a與已經(jīng)存在指定索引位置上數(shù)據(jù)以鏈表的方式存儲(chǔ)。
JDK 7:元素a放到數(shù)組中,指向原來(lái)的元素。
LDK 8:原來(lái)的元素在數(shù)組中,指向元素a
總結(jié):七上八下
HashSet底層:數(shù)組 + 鏈表的結(jié)構(gòu)(前提:JDK 7之前)

LinkedHashSet的使用
linkedHashSet作為HashSet的子類,在添加數(shù)據(jù)的同時(shí),每個(gè)數(shù)據(jù)還維護(hù)了兩個(gè)引用,記錄此數(shù)據(jù)前一個(gè)數(shù)據(jù)和后一個(gè)數(shù)據(jù)
優(yōu)點(diǎn):對(duì)于頻繁的遍歷操作,LinkedHashSet效率高于HashSet

public void test2(){
        HashSet set = new LinkedHashSet();
        set.add(456);
        set.add(123);
        set.add(123);
        set.add("AA");
        set.add("CC");
        set.add(new User("Tom",12));
        set.add(new User("Tom",12));
        set.add(129);
        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }
}

注意點(diǎn):

1.向TreeSet中添加的數(shù)據(jù),要求是相同類的對(duì)象。
2.兩種排序方式:自然排序(實(shí)現(xiàn)Comparable接口) 和 定制排序(Comparator)
3.自然排序中,比較兩個(gè)對(duì)象是否相同的標(biāo)準(zhǔn)為:compareTo()返回0.不再是equals().
定制排序中,比較兩個(gè)對(duì)象是否相同的標(biāo)準(zhǔn)為:compare()返回0.不再是equals().

4.TreeSet和后面要講的TreeMap采用紅黑樹(shù)的存儲(chǔ)結(jié)構(gòu);特點(diǎn):有序,查詢速度比List快

 public void test1(){
        TreeSet set = new TreeSet();
        //報(bào)錯(cuò):ClassCastException 不能添加不同類的對(duì)象
//        set.add(123);
//        set.add(456);
//        set.add("AA");
//        set.add(new User("Tom",12));
        //舉例一:
//        set.add(34);
//        set.add(-34);
//        set.add(43);
//        set.add(11);
//        set.add(8);
        //舉例二:
        set.add(new User("Tom",12));
        set.add(new User("Jerry",32));
        set.add(new User("Jim",2));
        set.add(new User("Mike",65));
        set.add(new User("Jack",22));
        set.add(new User("Jack",62));
        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
    @Test
    public void test2(){
        Comparator com = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof User && o2 instanceof User){
                    User u1 = (User)o1;
                    User u2 = (User)o2;
                    return Integer.compare(u1.getAge(),u2.getAge());
                }else{
                    throw new RuntimeException("輸入的類型不匹配");
                }
            }
        };
        TreeSet set = new TreeSet(com);
        set.add(new User("Tom",12));
        set.add(new User("Jerry",32));
        set.add(new User("Jim",22));
        set.add(new User("Mike",65));
        set.add(new User("Jack",22));
        set.add(new User("Jack",62));
        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

到此這篇關(guān)于深入淺出講解Java集合之Collection接口的文章就介紹到這了,更多相關(guān)Java Collection內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論