Java學習List介面、Set介面

來源:互聯網
上載者:User

標籤:boolean   etag   inf   rgs   class   返回   ast   不同   next   

Collection中常用的兩大子類(List集合、Set集合)

List介面

1、它是一個元素存取有序的集合。這裡的有序不是說集合按照升序降序進行儲存,而是說元素怎麼存進去,怎麼取出來的

2、它是一個帶有索引的集合,通過索引就可以精確的操作集合中的元素(與數組的索引是一個道理)。

3、 集合中可以有重複的元素,通過元素的equals方法,來比較是否為重複的元素。

List介面的常用子類有:

1、ArrayList集合

2、LinkedList集合

List中常用的方法:

package com.oracle.demo1;import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class ListDemo {public static void main(String[] args) {add();remove();set();get();        edit();}/* * void add(int index,E element) 在指定位置添加元素 * java.lang.IndexOutOfBoundsException 集合的越界異常 * java.lang.ArrayIndexOutOfBoundsException 數組的越界異常 * java.lang.StringIndexOutOfBoundsException 字串的越界異常 */public static void add() {List<String> list = new ArrayList<String>();list.add("asd");list.add("123");list.add("zxc");list.add(0, "xxx");System.out.println(list);}/* * E remove(int index)  * 1、刪除指定位置上的元素  * 2、返回被刪除的元素的值 */public static void remove() {List<String> list = new ArrayList<String>();list.add("asd");list.add("123");list.add("zxc");String element = list.remove(0);System.out.println(element);System.out.println(list);}/* * E set(int index,E element)  * 1、替換指定位置上的值 * 2、擷取替換之前的值 */public static void set() {List<String> list = new ArrayList<String>();list.add("asd");list.add("123");list.add("zxc");System.out.println(list);String e = list.set(1, "李四");System.out.println(e);}/* * E get(int index) * 擷取指定索引上的元素值 * */public static void get(){List<String> list = new ArrayList<String>();list.add("asd");list.add("123");list.add("zxc");System.out.println(list);System.out.println(list.get(0));for(int i=0;i<list.size();i++){           System.out.println(list.get(i));}System.out.println("=================");for(String e:list){System.out.println(e);}System.out.println("=================");Iterator<String> it=list.iterator();while(it.hasNext()){System.out.println(it.next());}}/* * Iterator並發修改異常 * java.util.ConcurrentModificationException * 在遍曆的過程中不能做修改長度的操作,不然會發生並發修改異常 * */public static void edit(){List<String> list = new ArrayList<String>();list.add("asd");list.add("123");list.add("zxc");Iterator<String> it=list.iterator();while(it.hasNext()){String str=it.next();if(str.equals("123")){int i=list.indexOf("123");list.add(i, "lisi");}System.out.println(list);}}
//並發修改異常解決辦法:在迭代時,不要使用集合的方法操作元素。

        //那麼想要在迭代時對元素操作咋辦?

        //通過ListIterator迭代器操作元素是可以的,ListIterator的出現,解決了使用Iterator迭代過程中可能會發生的錯誤情況。

}

List集合儲存的資料結構

資料存放區的常用結構有:堆棧、隊列、數組、鏈表

堆棧  採用該結構的集合,對元素的存取有如下的特點:

         先進後出(即,存進去的元素,要在後它後面的元素依次取出後,才能取出該元素)。例如,子彈壓進彈夾,先壓進去的子彈在下面,後壓進去的子彈在上面,當開槍時,先          彈出上面的子彈,然後才能彈出下面的子彈。

         棧的入口、出口的都是棧的頂端位置

         壓棧:就是存元素。即,把元素儲存到棧的頂端位置,棧中已有元素依次向棧底方向移動一個位置。

         彈棧:就是取元素。即,把棧的頂端位置元素取出,棧中已有元素依次向棧頂方向移動一個位置。

        

隊列 採用該結構的集合,對元素的存取有如下的特點:

        先進先出(即,存進去的元素,要在後它前面的元素依次取出後,才能取出該元素)。例如,安檢。排成一列,每個人依次檢查,只有前面的人全部檢查完畢後,才能排到當           前的人進行檢查。

        隊列的入口、出口各佔一側。例如,中的左側為入口,右側為出口。

       

數組 採用該結構的集合,對元素的存取有如下的特點:

         尋找元素快:通過索引,可以快速存取指定位置的元素

         增刪元素慢:

                            指定索引位置增加元素:需要建立一個新數組,將指定新元素儲存在指定索引位置,再把原數組元素根據索引,複製到新數組對應索引的位置。如

                            指定索引位置刪除元素:需要建立一個新數組,把原數組元素根據索引,複製到新數組對應索引的位置,原數組中指定索引位置元素不複製到新數組中。如

       

鏈表 採用該結構的集合,對元素的存取有如下的特點:

         多個節點之間,通過地址進行串連。例如,多個人手拉手,每個人使用自己的右手拉住下個人的左手,依次類推,這樣多個人就連在一起了。

        尋找元素慢:想尋找某個元素,需要通過串連的節點,依次向後尋找指定元素

        增刪元素快:

                          增加元素:操作如左圖,只需要修改串連下個元素的地址即可。

                          刪除元素:操作如右圖,只需要修改串連下個元素的地址即可。

        

ArrayList集合資料存放區的結構是數組結構,元素增刪慢,尋找快,所以日常開發中的查詢資料,遍曆資料,ArrayList集合是最常用的

LinkedList集合資料存放區的結構是鏈表結構,元素增刪快,尋找慢,在實際開發中對一個集合的增刪經常涉及到首尾操作,在LinkedList集合中提供了一下方法,如下

package com.oracle.demo2;import java.util.LinkedList;public class LinkedListDemo {public static void main(String[] args) {add();get();remove();}/* * void addFirst(E e) 將指定元素插入到此列表的開頭 void addLast(E e) 將指定元素插入到此列表的結尾 */public static void add() {LinkedList<String> list = new LinkedList<String>();list.addLast("好好學習");list.add("HelloWorld");list.addFirst("你好");System.out.println(list);}/* * E getFirst() 返回此列表的第一個元素  * E getLast() 返回此列表的最後一個元素 * java.util.NoSuchElementException * 當集合中沒有元素時再擷取元素會報異常 * boolean isEmpty()  如果列表中不包含元素,返回true */public static void get() {LinkedList<String> list = new LinkedList<String>();list.addLast("好好學習");list.add("HelloWorld");list.addFirst("你好");list.clear();if(!list.isEmpty()){String s = list.getFirst();String f = list.getLast();System.out.println(s + "=========" + f);}else{System.out.println("NoSuchElementException");}}/* * E removeFirst()  移除並返回列表中的第一個元素 * E removeLast()  移除並返回列表中的最後一個元素 * */public static void remove(){LinkedList<String> list = new LinkedList<String>();list.addLast("好好學習");list.add("HelloWorld");list.addFirst("你好");System.out.println(list.removeFirst());System.out.println(list.removeLast());System.out.println(list);}}

Vector集合

Vector集合資料存放區的結構是數組結構,為JDK中最早提供的集合。Vector中提供了一個獨特的取出方式,就是枚舉Enumeration,它其實就是早期的迭代器。此介面Enumeration的功能與 Iterator 介面的功能是類似的。Vector集合已被ArrayList替代。枚舉Enumeration已被迭代器Iterator替代。

Set介面

set介面的特點:和List介面的特點相反,無序、可重複、無索引

package com.oracle.demo3;import java.util.HashSet;import java.util.Iterator;import java.util.Set;public class SetDemo {public static void main(String[] args) {Set<String> set = new HashSet<String>();set.add("123");set.add("asd");set.add("w34ww");set.add("dvef");set.add("dvef");// set中沒有索引,無序// 1、用Iterator遍曆Iterator<String> it = set.iterator();while (it.hasNext()) {System.out.println(it.next());}System.out.println("===============");// 2、增強for迴圈for (String str : set) {System.out.println(str);}}}

執行結果

HashSet集合

HashSet 實現Set介面,由雜湊表支援(實際上是一個HashMap集合)

HashSet集合不能保證的迭代順序與元素儲存順序相同。

HashSet集合,採用雜湊表結構儲存資料,保證元素唯一性的方式依賴於:hashCode()與equals()方法。

package com.oracle.demo3;import java.util.HashSet;public class HashSetDemo {    public static void main(String[] args) {hash();}    /*     * set中儲存資料是不能重複的     * 1、計算你要儲存的對象的雜湊值,然後將這個雜湊值放到集合中去看看     *    有沒有相同的雜湊值     * 2、拿著雜湊值在集合中找,如果有相同的雜湊值,那麼就調用equals方法,     *    "aab".equals("aab"),如果相同,返回true,就判定這是個重複元素,丟掉     * 3、如果雜湊值相同,則調用equals方法,如果返回false,那麼存入set     * */    public static void hash(){    HashSet<String> hs=new HashSet<String>();    hs.add("aab");    hs.add("aab");    hs.add("bbc");    hs.add("bbc");        System.out.println(hs);    }}

執行結果:[bbc,aab]   說明set集合中是不能儲存重複元素的

HashSet儲存自訂類型的資料

如果要保證資料的唯一性依賴於:hashcode()和equals()方法

如果給HashSet中儲存JavaAPI中提供的類型的元素時,不需要重寫元素的hashcode和equals方法,

因為這兩個方法,在JavaAPI的每個類中已經重寫完畢,如String類、Integer類等。

給HashSet中存放自訂類型元素時,需要重寫對象中的hashCode和equals方法,建立自己的比較方式,才能保證HashSet集合中的對象唯一

package com.oracle.demo3;public class Person {String name;int age;    public int hashCode(){    return name.hashCode()+age*55;    }    public String toString(){    return "name為"+name+" age為"+age;    }    public boolean equals(Object obj){    if(obj==null){    return false;    }    if(this==obj){    return true;    }    if(obj instanceof Person){    return ((Person) obj).age==this.age&&((Person)obj).name==this.name;    }    return false;    }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;}public Person(String name, int age) {super();this.name = name;this.age = age;}public Person() {}}

 

package com.oracle.demo3;import java.util.HashSet;import java.util.Iterator;public class Test {public static void main(String[] args) {//建立hashset對象HashSet<Person> hs =new HashSet<Person>();hs.add(new Person("張三", 18));hs.add(new Person("李四", 58));hs.add(new Person("王五",30));hs.add(new Person("李四", 58));Iterator<Person> it=hs.iterator();while(it.hasNext()){Person p=(Person)it.next();System.out.println(p);}}}

  

LinkedHashSet集合

HashSet保證元素唯一,但是元素存放進去是沒有順序的,那麼我們要保證有序,就需要用到LinkedHashSet

在HashSet下面有一個子類LinkedHashSet,它是鏈表和雜湊表組合的一個資料存放區結構。

package com.oracle.demo3;import java.util.LinkedHashSet;public class LinkedHashSetDemo {     public static void main(String[] args) { LinkedHashSet<String> list=new LinkedHashSet<String>();        list.add("123");        list.add("asd");        list.add("3esd");        System.out.println(list);}}

判斷集合元素是否唯一的原理

ArrayList的contains方法判斷元素是否重複原理

ArrayList的contains方法會使用調用方法時,傳入的元素的equals方法依次與集合中的舊元素所比較,從而根據返回的布爾值判斷是否有重複元素。此時,當ArrayList存放自訂類型時,由於自訂類型在未重寫equals方法前,判斷是否重複的依據是地址值,所以如果想根據內容判斷是否為重複元素,需要重寫元素的equals方法。

HashSet的add/contains等方法判斷元素是否重複原理

Set集合不能存放重複元素,其添加方法在添加時會判斷是否有重複元素,有重複不添加,沒重複則添加。

HashSet集合由於是無序的,其判斷唯一的依據是元素類型的hashCode與equals方法的返回結果。規則如下:

先判斷新元素與集合內已經有的舊元素的HashCode值

       如果不同,說明是不同元素,添加到集合。

       如果相同,再判斷equals比較結果。返回true則相同元素;返回false則不同元素,添加到集合。

所以,使用HashSet儲存自訂類型,如果沒有重寫該類的hashCode與equals方法,則判斷重複時,使用的是地址值,如果想通過內容比較元素是否相同,需要重寫該元素類的hashcode與equals方法。

 

Java學習List介面、Set介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.