淺談關於collection介面及相關容器類(一),淺談collection

來源:互聯網
上載者:User

淺談關於collection介面及相關容器類(一),淺談collection


                 Collection在英文單詞的意思是:採集,收集。而在JAVA API 文檔中它是一個收集資料對象的容器。

          Collection作為容器類的根介面。如(部分子介面未寫出):

             

                                 

              文檔中說明了Collection介面,有如下的方法:

boolean add(E e)Ensures that this collection contains the specified element (optional operation).
boolean addAll(Collection<? extendsE> c)Adds all of the elements in the specified collection to this collection (optional operation).
void clear()Removes all of the elements from this collection (optional operation).
boolean contains(Object o)Returns true if this collection contains the specified element.
boolean containsAll(Collection<?> c)Returns true if this collection contains all of the elements in the specified collection.
boolean equals(Object o)Compares the specified object with this collection for equality.
int hashCode()Returns the hash code value for this collection.
boolean isEmpty()Returns true if this collection contains no elements.
Iterator<E> iterator()Returns an iterator over the elements in this collection.
boolean remove(Object o)Removes a single instance of the specified element from this collection, if it is present (optional operation).
boolean removeAll(Collection<?> c)Removes all of this collection's elements that are also contained in the specified collection (optional operation).
boolean retainAll(Collection<?> c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
int size()Returns the number of elements in this collection.
Object[] toArray()Returns an array containing all of the elements in this collection.
<T> T[] toArray(T[] a)Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
                中,Set與List、Map都是Collection的子類。它們的區別在於,Set實現的類只能存放無序、無重複的資料對象,而List只存放的是有序,可重複的資料對象;Map介面定義了儲存著"鍵(key)-值(value)映射對的方法。

         下面代碼示範List繼承collection介面並實現它部分的相關方法:

         

<pre name="code" class="java">     package CrazyStone;import java.util.ArrayList;import java.util.List;public class DemoList {   public static void main(String[] args) {int value;    List list=new  ArrayList();                            //定義List類對象list,並實現父類引用;    list.add("CSDN");            //添加資料對象方法;    list.add("GB記憶");                   System.out.println(   list.isEmpty());       //判斷list容器是否為空白        value=list.size();              //返回容器的大小;        for(int i=0;i<value;i++)       //遍曆容器;        {  String str =(String) list.get(i);            System.out.println(str);                }        System.out.println("---------------------");      //跟順序有關的操作        list.remove(0);               //在容器中移出CSDN,但並未刪除;        list.set(0, "CSDNGO");  //向容器中插入對象;       list.add("加油!");       value=list.size();        for(int i=0;i<value;i++)       //遍曆容器;       {  String str =(String) list.get(i);           System.out.println(str);              }}   }


        

                  

                 


6集合介面Map,collection的不同

Collection:List、Set
Map:HashMap、HashTable

如何在它們之間選擇

一、Array , Arrays

Java所有“儲存及隨機訪問一連串對象”的做法,array是最有效率的一種。

1、
效率高,但容量固定且無法動態改變。
array還有一個缺點是,無法判斷其中實際存有多少元素,length只是告訴我們array的容量。

2、Java中有一個Arrays類,專門用來操作array。
arrays中擁有一組static函數,
equals():比較兩個array是否相等。array擁有相同元素個數,且所有對應元素兩兩相等。
fill():將值填入array中。
sort():用來對array進行排序。
binarySearch():在排好序的array中尋找元素。
System.arraycopy():array的複製。

二、Collection , Map

若撰寫程式時不知道究竟需要多少對象,需要在空間不足時自動擴增容量,則需要使用容器類庫,array不適用。

1、Collection 和 Map 的區別

容器內每個為之所儲存的元素個數不同。
Collection類型者,每個位置只有一個元素。
Map類型者,持有 key-value pair,像個小型資料庫。

2、各自旗下的子類別關係

Collection
--List: 將以特定次序儲存元素。所以取出來的順序可能和放入順序不同。
--ArrayList / LinkedList / Vector
--Set : 不能含有重複的元素
--HashSet / TreeSet
Map
--HashMap
--HashTable
--TreeMap

3、其他特徵

* List,Set,Map將持有對象一律視為Object型別。
* Collection、List、Set、Map都是介面,不能執行個體化。
繼承自它們的 ArrayList, Vector, HashTable, HashMap是具象class,這些才可被執行個體化。
* vector容器確切知道它所持有的對象隸屬什麼型別。vector不進行邊界檢查。

三、Collections

Collections是針對集合類的一個協助類。提供了一系列靜態方法實現對各種集合的搜尋、排序、線程完全化等操作。
相當於對Array進行類似操作的類——Arrays。
如,Collections.max(Collection coll); 取coll中最大的元素。
Collections.sort(List list); 對list中元素排序

四、如何選擇?

1、容器類和Array的區別、擇取
* 容器類僅能持有對象引用(指向對象的指標),而不是將對象資訊copy一份至數列某位置。
* 一旦將對象置入容器內,便損失了該對象的型別資訊。

2、
* 在各種Lists中,最好的做法是以ArrayList作為預設選擇。當插入、刪除頻繁時,使用LinkedList();
Vector總是比ArrayList慢,所以要盡量避免使用。
* 在各種Sets中,HashSet通常優於HashTree(插入、尋找)。只有當需要產生一個經過排序的序列,才用TreeSet。
HashTree存在的唯一理由:能夠維護其內元素的排序狀態。
* ......餘下全文>>
 
java容器類與集合類是一個概念?

編輯詞條JAVA容器
解釋一:
容器(Container)
Spring 提供容器功能,容器可以管理對象的生命週期、對象與對象之間的依賴關係,您可以使用一個設定檔(通常是XML),在上面定義好對象的名稱、如何產生(Prototype 方式或Singleton 方式)、哪個對象產生之後必須設定成為某個對象的屬性等,在啟動容器之後,所有的對象都可以直接取用,不用編寫任何一行程式碼來產生對象,或是建立對象與對象之間的依賴關係。
換個更直白點的說明方式:容器是一個Java 所編寫的程式,原先必須自行編寫程式以管理對象關係,現在容器都會自動幫您作好。
常用容器:WebSphere,WebLogic,Resin,Tomcat
----------------------------------
解釋二:
容器類
Java容器類包含List、ArrayList、Vector及map、HashTable、HashMap
ArrayList和HashMap是非同步,Vector和HashTable是同步的,所以Vector和HashTable是安全執行緒的,而 ArrayList和HashMap並不是安全執行緒的。因為同步需要花費機器時間,所以Vector和HashTable的執行效率要低於 ArrayList和HashMap。
Collection
├List 介面
│├LinkedList 鏈表
│├ArrayList 順序結構動態數組類
│└Vector 向量
│ └Stack 棧
└Set
Map
├Hashtable
├HashMap
└WeakHashMap List介面
List是有序的Collection,使用此介面能夠精確的控制每個元素插入的位置。使用者能夠使用索引(元素在List中的位置,類似於數組下標)來訪問List中的元素,這類似於Java的數組。
和下面要提到的Set不同,List允許有相同的元素。
除了具有Collection介面必備的iterator()方法外,List還提供一個listIterator()方法,返回一個 ListIterator介面,和標準的Iterator介面相比,ListIterator多了一些add()之類的方法,允許添加,刪除,設定元素, 還能向前或向後遍曆。
實現List介面的常用類有LinkedList,ArrayList,Vector和Stack。
ArrayList類
ArrayList實現了可變大小的數組。它允許所有元素,包括null。ArrayList沒有同步。
size,isEmpty,get,set方法已耗用時間為常數。但是add方法開銷為分攤的常數,添加n個元素需要O(n)的時間。其他的方法已耗用時間為線性。
每個ArrayList執行個體都有一個容量(Capacity),即用於儲存元素的數組的大小。這個容量可隨著不斷添加新元素而自動增加,但是增長演算法 並沒有定義。當需要插入大量元素時,在插入前可以調用ensureCapacity方法來增加ArrayList的容量以提高插入效率。
和LinkedList一樣,ArrayList也是非同步的(unsynchronized)。
Map介面
請注意,Map沒有繼承Collection介面,Map提供key到value的映射。一個Map中不能包含相同的key,每個key只能......餘下全文>>
 

聯繫我們

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