Java 中的集合介面——List、Set、Map

來源:互聯網
上載者:User

標籤:clear   lis   尋找   局限性   iterator   輸出   import   ati   效能   

Java 中的集合介面——List、Set、Map

 

什麼叫集合:集合就是Java API所提供的一系列類的執行個體,可以用於動態存放多個對象。這跟我們學過的數組差不多,那為什麼我們還要學集合,我們看看數組跟集合有什麼區別:

數組:長度固定,遍曆速度快 可以儲存基本類型和參考型別;

集合:長度不固定,只能儲存參考型別對象;

從數組跟集合的特點我們很明顯的看出,數組有一定的局限性,如果我們需要不週期性往我們的資料中儲存資料,數組就滿足不了我們的要求。

Java集合架構提供了一套效能優良、使用方便的介面和類,它們位於java.util包中 

 

Collection 介面儲存一組不唯一,無序的對象 ;List 介面儲存一組不唯一,有序(插入順序)的對象;

Set 介面儲存一組唯一,無序的對象;Map介面儲存一組索引值對象,提供key到value的映射

對於collection介面中的一些方法,我們用實際代碼來學習一下吧:

import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;/** * Collection * 集合基本操作 * 添加 * 刪除 * 遍曆 * 判斷 * 尋找 * @author shen_hua * */public class CollectionDemo {    public static void main(String[] args) {        Collection<String> collection=new ArrayList<String>();        System.out.println("元素個數:"+collection.size());                //添加元素        collection.add("aaa");        collection.add("bbb");        collection.add("ccc");        System.out.println("增加後元素的個數:"+collection.size());//        //刪除元素//        collection.remove("bbb");//        System.out.println("刪除後元素的個數:"+collection.size());//        collection.clear();//        System.out.println("清空後元素的個數:"+collection.size());        //增強for迴圈遍曆        System.out.println("增強for迴圈輸出:");        for (Object object : collection) {            System.out.println(object);        }        //迭代器遍曆        System.out.println("迭代器遍曆:");        Iterator<String> iterator=collection.iterator();        while(iterator.hasNext()){            System.out.println(iterator.next());        }        //判斷是否包含        Boolean boolean1=collection.contains("aaa");        System.out.println(boolean1);        //判斷是否為空白        Boolean boolean2=collection.isEmpty();        System.out.println(boolean2);    }}

Iterator介面:所有實現了Collection介面的集合類都有一個iterator()方法用以返回一個實現了Iterator介面的對象: Iterator it = coll.iterator();

Iterator迭代器的工作原理:Iterator是專門的迭代輸出介面。所謂的迭代輸出就是將元素進行判斷,判斷是否有內容,如果有內容則把內容取出。 Iterator對象稱作迭代器,用以方便的實現對集合內元素的遍曆操作。

凡是能用 Iterator 迭代的集合都可以用JDK5.0中增強for迴圈來更簡便的遍曆。

List介面:

Java 中的集合介面——List、Set、Map

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.