轉(zhuǎn)載自:Java集合框架實(shí)例
1- 介紹
集合是程序和語(yǔ)言的基本思想。應(yīng)用程序通常都會(huì)應(yīng)用到集合,例如雇員的信息,圖像的收集等的存儲(chǔ)。像其他語(yǔ)言,Java還支持?jǐn)?shù)組作為最基本的集合。然而,數(shù)組在許多情況下工作并不是那么方便,因?yàn)閿?shù)組生命周期,增加元素或移除元素是非常困難的,甚至需要程序付出效率。
下圖說明了一個(gè)數(shù)組的操作:
2- 第一個(gè)示例
首先,我們有鏈表(LinkedList)的例子。它是元素?cái)?shù)不像數(shù)組一樣限制的多變列表。
HelloLinkedList.java
package com.yiibai.tutorial.javacollection.helloworld;
import java.util.LinkedList;
public class HelloLinkedList {
? ? public static void main(String[] args) {
? ? ? ? // Create collection object - LinkedList
? ? ? ? LinkedList list = new LinkedList();
? ? ? ? // Add elements to the linked list
? ? ? ? list.add("F");
? ? ? ? list.add("B");
? ? ? ? list.add("D");
? ? ? ? list.add("E");
? ? ? ? list.add("C");
? ? ? ? // Appends the specified element to the end of this list.
? ? ? ? list.addLast("Z");
? ? ? ? list.addFirst("A");
? ? ? ? // Inserts the specified element at the beginning of this list.
? ? ? ? list.add(1, "A2");
? ? ? ? // Print out, all elements
? ? ? ? System.out.println("Original contents of list: " + list);
? ? ? ? // Remove elements from the linked list
? ? ? ? list.remove("F");
? ? ? ? // Remove the element at index 2.
? ? ? ? list.remove(2);
? ? ? ? // Print out the list, after removing two elements.
? ? ? ? System.out.println("Contents of list after deletion: " + list);
? ? ? ? // Remove first and last elements
? ? ? ? list.removeFirst();
? ? ? ? list.removeLast();
? ? ? ? // Print out collection
? ? ? ? System.out.println("List after deleting first and last: " + list);
? ? ? ? // Get and set a value
? ? ? ? Object val = list.get(2);
? ? ? ? // Set element at index 2
? ? ? ? list.set(2, (String) val + " Changed");
? ? ? ? System.out.println("List after change: " + list);
? ? }
}
運(yùn)行示例的結(jié)果:
使用HashMap的一個(gè)例子。這是一種含有對(duì)的鍵/值的對(duì)象。考慮一個(gè)實(shí)例:電話簿,電話號(hào)碼是一個(gè)鍵,同時(shí)用戶的信息是一個(gè)值。鍵必須是不一樣的。
HelloHashMap.java
package com.yiibai.tutorial.javacollection.helloworld;
import java.util.HashMap;
public class HelloHashMap {
? ? public static void main(String[] args) {
? ? ? ? // Create a HashMap objects, store employee-code and salaries.
? ? ? ? // String key: Employee-code
? ? ? ? // Float value: Salary
? ? ? ? HashMap salaryMap = new HashMap();
? ? ? ? salaryMap.put("E01", 1000f);
? ? ? ? salaryMap.put("E02", 12000f);
? ? ? ? salaryMap.put("E03", 12300f);
? ? ? ? salaryMap.put("E04", 1000f);
? ? ? ? salaryMap.put("E05", 300.5f);
? ? ? ? // Get the salary of employee 'E02'
? ? ? ? Float salary= salaryMap.get("E01");
? ? ? ? System.out.println("Salary of employee E01 = "+ salary);
? ? ? ? // Change the salary for employee 'E05'
? ? ? ? salaryMap.put("E05", 400f);
? ? ? ? System.out.println("Salary of employee E05 = "+ salaryMap.get("E05"));
? ? }
}
運(yùn)行示例的結(jié)果:
Salary of employee E01 = 1000.0
Salary of employee E05 = 400.0
3-?使用數(shù)組的局限性?-?一個(gè)建議來解決這個(gè)問題
3.1- 數(shù)組是一個(gè)基本的集合類型
數(shù)組是非常基本的也是大家最熟悉的。
存儲(chǔ)引用類型,基本類型
int[] myArray=new int[]{1,4,3};
Object[] myArrayObj =new Object[]{"Object",new Integer(100)};
數(shù)組具有固定的大小和尺寸。
這使得數(shù)組難以擴(kuò)展
元件排列并順序地引用在內(nèi)存中。
這使得難以從數(shù)組中刪除指定的元素。
3.2-?從數(shù)組中刪除元素
數(shù)組中的元素是連續(xù)排列在內(nèi)存中的,所以如果你有意數(shù)組要?jiǎng)h除一個(gè)元素是比較困難的,因?yàn)樗鼤?huì)失去了延續(xù)性。通常情況下,在技術(shù)上創(chuàng)建一個(gè)新的數(shù)組是存儲(chǔ)上次的數(shù)組對(duì)象并丟棄不必要的元素,但這種降低了程序的執(zhí)行效率。類似的技術(shù)被應(yīng)用到數(shù)組的擴(kuò)展,在此我們會(huì)以更大的空間來創(chuàng)建一個(gè)新的數(shù)組,然后將之前的數(shù)組元素復(fù)制到新的的數(shù)組。
顯然,這種數(shù)組應(yīng)用在應(yīng)用程序中在許多情況下不是好方法。
3.3-?鏈表
鏈表是克服的數(shù)組的弱點(diǎn)數(shù)據(jù)管理方式之一。當(dāng)然,也有在Java管理列表的各種方法,例如:ArrayList
讓我們來看看鏈表(LinkedList)的特點(diǎn):?
在這個(gè)列表中的元素可以在存儲(chǔ)器中,不連續(xù)地分離出來。
它是元素間雙向鏈路。
列表中的每個(gè)元素,使它前面的元素和它后面的元素的引用。
鏈表是一個(gè)雙向鏈路。
鏈接元素是需要管理一個(gè)包含對(duì)象的數(shù)據(jù)。它有兩個(gè)引用鏈接元素的前面和后面。
就像一群人在排隊(duì),每個(gè)人需要記住兩個(gè)人 -?站面前和在后面他/她。
移除LinkedList的一個(gè)元素
移除LinkedList的一個(gè)元素是一樣的去除類似站在隊(duì)列的人。?靠近此人兩個(gè)人不得不重新更新的人面前,背后的人。
添加元素到鏈表中(在末尾或在鏈表中)
總之,雖然我們只是有一個(gè)鏈表的例子,它可以幫助我們理解java.util包更多的信息。
注:鏈表方案是解決數(shù)組的一個(gè)弱點(diǎn)。?ArrayList是管理數(shù)據(jù)集合的方法。它可以處理數(shù)組的弱點(diǎn),但它管理數(shù)據(jù)的方式與LinkedList是不同的。
4-?Java?Collections框架概述
意識(shí)到數(shù)組局限性,從版本Java1.0就有java.util.Vector,是對(duì)象的類存儲(chǔ)列表。?java.util.Hashtable是一個(gè)存儲(chǔ)對(duì)鍵/值的類。其次,Java?2平臺(tái)仍在不斷推出接近集合的方式,命名為集合框架。java.util.Vector,java.util.Hashtable依然存在,現(xiàn)在是巨大的平臺(tái)的一部分。?這些集合都建在java.util包中一些接口的基礎(chǔ)上。它們被分成由2個(gè)接口主導(dǎo)兩個(gè)層次結(jié)構(gòu)系統(tǒng),java.util.Collection包含對(duì)象和鍵/值對(duì)的java.util.Map列表。
4.1-?Java集合框架接口
上面的圖片是Java?Collections?Framework的重要接口。我們將把它們按用途和用法討論這些接口的使用目的。在java.util包,類實(shí)現(xiàn)一個(gè)或多個(gè)這些接口。?因此,java.util中的類可以具有許多不同的功能。例如,java.util.HashMap:
Class?Hashtable:
public class HashMap extends AbstractMap
? ? ? ? ? ? ? ? ? ? ? ? ? implements Map, Cloneable, Serializable
Class?Vector:
public class Vector extends AbstractList
? ? ? ? ? ? implements List, RandomAccess, Cloneable, Serializable
4.2-?接口集合和映射引導(dǎo)兩個(gè)層次-?數(shù)據(jù)存儲(chǔ)方法
集合組存儲(chǔ)對(duì)象。
在集合組三個(gè)子分支:?Queue,?List, 和?Set.
元素可以是相似或不相似這取決于它們的分支。?(更多細(xì)節(jié)將在后面討論)。
映射組存儲(chǔ)key和value對(duì)
映射的鍵是不允許相同的。
如果我們知道鍵,就可以提取等于其映射鍵對(duì)應(yīng)的值。
在引用類型的形式集合組存儲(chǔ)數(shù)據(jù),MAP組存儲(chǔ)對(duì)鍵和值。
Collection c=new ArrayList();
// Add elements to collection
c.add("One");
Map m=new LinkedHashMap();
Integer key=new Integer(123);
String value="One two three";
// Associates the specified value with the specified key in this map.
// If the map previously contained a mapping for the key, the old
// value is replaced.
m.put(key,value);
//
System.out.println(m.get(new Integer(123));
4.3-?接口迭代器和隨機(jī)訪問?-?數(shù)據(jù)訪問方法
java.util.Iterator
要檢索數(shù)據(jù),從一個(gè)元素到另一個(gè)元素依次訪問迭代器。
java.util.RandomAccess
隨機(jī)接入方法,例如定位元素和設(shè)定檢索該元素
例如,java.util.Vector實(shí)現(xiàn)了這個(gè)接口,可以檢索隨機(jī)元素使用vector.get?(int?index)。
集合組也可以反過來通過調(diào)用方法iterator()?來檢索訪問Iterator對(duì)象。
java.util.Collection接口是從java.lang.Iterable擴(kuò)展,所以它繼承了public?Iterator?iterator()?方法,來迭代集合的元素。
在上述2個(gè)接口迭代器和隨機(jī)訪問的示例,它代表了兩種方法如何訪問一個(gè)集合中的元素。
看看?Vector?類:
public class Vector extends AbstractList
? ? ? ? ? ? ? implements List, RandomAccess, Cloneable, Serializable
Vector屬于集合組,可以通過get?(index)?方法訪問,或通過迭代器,或隨機(jī)訪問來元素。
注:對(duì)于列表組類,也可以檢索對(duì)象的ListIterator,?這個(gè)迭代器可以讓你在列表中向后或向前僅向前的光標(biāo)位置,而不是像迭代器一樣。
5-?集合組
5.1-?集合組中的接口
集合有三種直接子接口:Queue,List和Set。其中,Queue從1.5版本中增加,并考慮為這是一個(gè)等待隊(duì)列。Queue也有一個(gè)子接口:BlockingQueue,屬于java.util.concurrent包,?但我們沒有在這節(jié)教程中討論。Queue是一個(gè)包含許多定義以及組織我們需要最注重的接口方式。三個(gè)接口Queue?,?List?,?Set被視為集合組的三個(gè)分支。
在學(xué)習(xí)這幾個(gè)組的細(xì)節(jié)之前,讓我們來看看Collection接口的概述。
5.2- java.util.Collection接口
繼承關(guān)系
java.util.Collection
public interface Collection extends java.lang.Iterable {
? //
? // Add element to collection
? // return true if this collection changed as a result of the call
? //
? boolean add(E o);
? //
? // Adds all of the elements in the specified collection to this collection.
? // return true if this collection changed as a result of the call
? //
? boolean addAll(Collection c);
? // Removes all of the elements from this collection (optional operation).
? // The collection will be empty after this method returns.
? void clear();
? // Returns true if this collection contains the specified element.
? boolean contains(Object o);
? // Returns true if this collection contains all of the elements
? // in the specified collection.
? boolean containsAll(Collection c);
? // Compares the specified object with this collection for equality
? boolean equals(Object o);
? int hashCode();
? // Returns true if this collection contains no elements.
? boolean isEmpty();
? //
? // Removes a single instance of the specified element from this
? // collection, if it is present (optional operation).
? //
? boolean remove(Object o);
? // Removes all of this collection's elements that are also contained in the
? // specified collection (optional operation)
? boolean removeAll(Collection c);
? //
? // Retains only the elements in this collection that are contained in the
? // specified collection (optional operation)
? //
? boolean retainAll(Collection c);
? // Returns the number of elements in this collection
? int size();
? // Returns an array containing all of the elements in this collection
? Object[] toArray();
? T[] toArray(T[] a);
? // Returns an iterator over the elements in this collection.
? Iterator iterator();
}
5.3-?訪問集合中的元素
集合中的元素迭代器。
例如,使用迭代訪問集合的元素。
CollectionAndIterator.java
package com.yiibai.tutorial.javacollection.collection;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;
public class CollectionAndIterator {
? ? public static void main(String[] args) {
? ? ? ? // Create empty collection
? ? ? ? // A Collection containing only String.
? ? ? ? Collection coll = new Vector();
? ? ? ? coll.add("Collection");
? ? ? ? coll.add("Queue");
? ? ? ? coll.add("List");
? ? ? ? coll.add("Map");
? ? ? ? // Print out the number of elements in this collection
? ? ? ? System.out.println("Size:" + coll.size());
? ? ? ? // Returns an iterator over the elements in this collection.
? ? ? ? // This Iterator containing only String.
? ? ? ? Iterator ite = coll.iterator();
? ? ? ? // Returns true if the iteration has more elements
? ? ? ? while (ite.hasNext()) {
? ? ? ? ? ? // Returns the next element in the iteration.
? ? ? ? ? ? String s = ite.next();
? ? ? ? ? ? System.out.println("Element:" + s);
? ? ? ? }
? ? }
}
運(yùn)行實(shí)例的結(jié)果:
Size:4
Element:Collection
Element:Queue
Element:List
Element:Map
5.4-?集合的分支
正如上面所說的,集合有三個(gè)子接口,包括Queue?,List 和 Set。它們之間的差別是存儲(chǔ)數(shù)據(jù)的方式。
java.util.Queuejava.util.Listjava.util.Set
允許包含重復(fù)的元素允許包含重復(fù)的元素不允許重復(fù)的元素
不允許包含null元素允許包含一個(gè)或多個(gè)null元素根據(jù)不同的類實(shí)現(xiàn)Set接口,是否支持包含空元素。如果支持,它僅包含至多有一個(gè)null元素。
一個(gè)列表(List)的目的,是一個(gè)相同的對(duì)象很可能出現(xiàn)不止一次的有序列表。?例如 : [1, 7, 1, 3, 1, 1, 1, 5].?說說在列表中的“第三個(gè)元素”是很有意義的。?可以在列表的任意位置添加元素,在列表中的任何位置更改元素,或從列表中的任何位置刪除元素。
-?隊(duì)列也是有順序的,但你永遠(yuǎn)只能觸及一端的元素。元素被插入在“結(jié)尾”,并從隊(duì)列中的“開頭”(或頭部)刪除。你可以知道在隊(duì)列中有多少個(gè)元素,但不能找出說,“第三個(gè)”元素是什么。當(dāng)你到達(dá)那里,你會(huì)看到它。
一個(gè)集合(Set)不是有序的,也不能包含重復(fù)的元素。任何給定的對(duì)象是不在集合中的。{7, 5, 3, 1}?集合是確實(shí)相同于 {1, 7, 1, 3, 1, 1, 1, 5}. 因此無法要求提供“第三個(gè)”元素,甚至“第一”的元素,因?yàn)樗鼈儾灰匀魏翁囟ǖ捻樞颉?您可以添加或刪除元素,也可以找出某個(gè)元素是否存在(例如,“7在這一集合中?”)
5.5- java.util.List 接口
列表(List)是集合(Collection)的子接口。它擁有Collection的全部功能,以及一些特殊的功能:
允許重復(fù)元素
允許零個(gè)或多個(gè)null元素存在。
列表(List)是對(duì)象的有序列表
除了通過使用迭代訪問,我們可以通過使用 ListIterator 訪問。允許 ListIterator 向前或向后移動(dòng)光標(biāo)。
// Returns a list iterator over the elements in this list?
public ListIterator listIterator() c?a list .
// Returns a list iterator over the elements in this list (in proper
// sequence), starting at the specified position in the list..
public ListIterator listIterator(int index) :
ListAndListIterator.java
package com.yiibai.tutorial.javacollection.list;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class ListAndListIterator {
? ? public static void main(String[] args) {
? ? ? ? // Create List object (Containing only String)
? ? ? ? List list = new ArrayList();
? ? ? ? list.add("One");
? ? ? ? list.add("Two");
? ? ? ? list.add("Three");
? ? ? ? list.add("Four");
? ? ? ? // Returns a list iterator over the elements in this list
? ? ? ? // (in proper sequence)
? ? ? ? ListIterator listIterator = list.listIterator();
? ? ? ? // Currently the cursor at the first position of the interator.
? ? ? ? // (Index 0).
? ? ? ? // Get the first element in the interator, the cursor forward one step.
? ? ? ? String first = listIterator.next();
? ? ? ? System.out.println("first:" + first);// -->"One"
? ? ? ? // Current cursor at index 1
? ? ? ? // Get next element.
? ? ? ? String second = listIterator.next();
? ? ? ? System.out.println("second:" + second);// -->"Two"
? ? ? ? // true if the list iterator has more elements when
? ? ? ? // traversing the list in the reverse direction
? ? ? ? if (listIterator.hasPrevious()) {
? ? ? ? ? ? // the previous element in the list
? ? ? ? ? ? String value = listIterator.previous();
? ? ? ? ? ? System.out.println("value:" + value);// -->"Two"
? ? ? ? }
? ? ? ? System.out.println(" ----- ");
? ? ? ? while (listIterator.hasNext()) {
? ? ? ? ? ? String value = listIterator.next();
? ? ? ? ? ? System.out.println("value:" + value);
? ? ? ? }
? ? }
}
運(yùn)行實(shí)例的結(jié)果:
first:One
second:Two
value:Two
-----
value:Two
value:Three
value:Four
5.6- java.util.Set接口
Set是Collection的子接口。它擁有集合的全部功能,以及其他一些特點(diǎn):
描述了一組不允許重復(fù)元素的集合
允許一個(gè)空元素的存在,如果有的話。
HashSetExample.java
package com.yiibai.tutorial.javacollection.set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class HashSetExample {
? ? public static void main(String[] args) {
? ? ? ? // Create a Set object with initial capacity 10
? ? ? ? // Automatically increase capacity 80% if the number of elements to
? ? ? ? // overcome the current capacity.
? ? ? ? // HashSet (LIFO - Last in first out)
? ? ? ? //? (element to be added later will stand first).
? ? ? ? Set set = new HashSet(10, (float) 0.8);
? ? ? ? set.add("One");
? ? ? ? set.add("Two");
? ? ? ? // Duplication occurs.
? ? ? ? // With HashSet: It will add new element, and remove the old element.
? ? ? ? set.add("One");
? ? ? ? set.add("Three");
? ? ? ? Iterator it = set.iterator();
? ? ? ? while (it.hasNext()) {
? ? ? ? ? ? System.out.println(it.next());
? ? ? ? }
? ? }
}
運(yùn)行實(shí)例的結(jié)果:
One
Two
Three
5.7- java.util.Queue接口
Queue是Collection的子類型的接口,它充滿著集合的特點(diǎn),相當(dāng)類似于列表(List),但是,使用目的略有不同。隊(duì)列(Queue)被設(shè)計(jì)成只能訪問第一個(gè)元素(刪除元素時(shí))在隊(duì)列中,它會(huì)刪除隊(duì)列的第一個(gè)元素。有點(diǎn)類似于人在超市排隊(duì)一樣,只有在隊(duì)列的頭部將可訪問,新人如要插入到該隊(duì)列中,插入位置可能不是隊(duì)列的末尾。插入的元素位置取決于隊(duì)列的類型和元素的優(yōu)先級(jí)。
隊(duì)列允許元素重復(fù)
不允許null元素
有兩個(gè)類都實(shí)現(xiàn)了Queue接口:
java.util.LinkedList
java.util.PriorityQueue
LinkedList是一個(gè)非常標(biāo)準(zhǔn)的隊(duì)列實(shí)現(xiàn)。但請(qǐng)記住,LinkedList同時(shí)實(shí)現(xiàn)List和Queue接口。
PriorityQueue根據(jù)自己的自然順序存儲(chǔ)的元素(如果它們實(shí)現(xiàn)Comparable)或者根據(jù)Comparator?傳遞給PriorityQueue。請(qǐng)注意,一個(gè)類可以實(shí)現(xiàn)了List?和Queue接口,所以你不需要關(guān)心元素是如何安排在上述內(nèi)部類的,如果把它作為一個(gè)隊(duì)列,請(qǐng)參閱訪問隊(duì)列中元素的方式。考慮隊(duì)列的典型方法,它模擬人在超市排隊(duì)隊(duì)列。
拋出異常返回指定值
Insertadd(e)offer(e)
Removeremove()poll()
Examineelement()peek()
boolean add(E)
將指定的元素插入此隊(duì)列中,如果它是立即可行且不違反容量限制,成功則返回true,如果當(dāng)前沒有空間可用則拋出IllegalStateException。
boolean offer(E)
將指定的元素插入此隊(duì)列中,如果它是立即可行且不違反容量限制。當(dāng)使用有容量限制的隊(duì)列通常是使用?add(E)方法,它可能在無法插入的元素時(shí)拋出異常?。
E remove()
檢索并移除此隊(duì)列的頭元素。該方法與poll不同在于如果此隊(duì)列為空,它會(huì)拋出一個(gè)異常。
E poll()
檢索,但是不移除此隊(duì)列的頭元素。這種方法與 peek 方法不同,如果此隊(duì)列為空它拋出一個(gè)異常。
E element()
檢索,但是不移除此隊(duì)列的頭元素。這種方法與peek方法不同,如果此隊(duì)列為空它拋出一個(gè)異常。
E peek()
檢索,但是不移除此隊(duì)列的頭元素,或者如果此隊(duì)列為空則返回null。
解釋:
除了上面提到的隊(duì)列方法外,您可以在隊(duì)列中訪問其他元素,除了第一個(gè)元素,也不能指定將被插入元素的位置。
QueueDemo.java
package com.yiibai.tutorial.javacollection.queue;
import java.util.LinkedList;
import java.util.Queue;
public class QueueDemo {
? ? public static void main(String[] args) {
? ? ? ? Queue names = new LinkedList();
? ? ? ? // offer(E): Insert element to queue.
? ? ? ? // With LinkedList, element will inserted at the end of queue.
? ? ? ? // Return true if success.
? ? ? ? // Return false if queue full.
? ? ? ? names.offer("E");
? ? ? ? names.offer("A");
? ? ? ? names.offer("M");
? ? ? ? // add(E): Insert element to queue
? ? ? ? // With LinkedList, element will inserted at the end of queue.
? ? ? ? // Return true if success.
? ? ? ? // Throw exception if queue full.? ?
? ? ? ? names.add("G");
? ? ? ? names.add("B");
? ? ? ? while (true) {? ? ?
? ? ? ? ? ? // Retrieves and removes the head of this queue,
? ? ? ? ? ? // or returns null if this queue is empty.
? ? ? ? ? ? String name = names.poll();
? ? ? ? ? ? if (name == null) {
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? ? ? System.out.println("Name=" + name);
? ? ? ? }
? ? }
}
運(yùn)行實(shí)例的結(jié)果:
Name=E
Name=A
Name=M
Name=G
Name=B
例如,使用一個(gè)優(yōu)先隊(duì)列PriorityQueue。此隊(duì)列在內(nèi)部根據(jù)自己的自然順序(如果實(shí)現(xiàn)Comparable),或者根據(jù)傳遞給PriorityQueue比較器(Comparator?)來存儲(chǔ)它的元素。
String就是實(shí)現(xiàn)了Comparable接口的類,它們可以相互比較后并按字母順序排列。
PriorityQueueDemo.java
package com.yiibai.tutorial.javacollection.queue;
import java.util.PriorityQueue;
import java.util.Queue;
public class PriorityQueueDemo {
? ? public static void main(String[] args) {
? ? ? ? // With PriorityQueue queue, the elements will be arranged on the natural order
? ? ? ? Queue names = new PriorityQueue();
? ? ? ? // offer(E): Insert element to queue
? ? ? ? // Return true if success
? ? ? ? // Return false if queue is full.
? ? ? ? names.offer("E");
? ? ? ? names.offer("A");
? ? ? ? names.offer("M");
? ? ? ? // add(E): Insert element to queue.
? ? ? ? // Return true if success
? ? ? ? // Throw exceptiono if queue is full.
? ? ? ? names.add("G");
? ? ? ? names.add("B");
? ? ? ? while (true) {
? ? ? ? ? ? // Retrieves and removes the head of this queue,
? ? ? ? ? ? // or returns null if this queue is empty.
? ? ? ? ? ? String name = names.poll();
? ? ? ? ? ? if (name == null) {
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? ? ? System.out.println("Name=" + name);
? ? ? ? }
? ? }
}
運(yùn)行實(shí)例的結(jié)果:
Name=A
Name=B
Name=E
Name=G
Name=M
5.8-?Collection組類之間的繼承關(guān)系
一些常見的類:
實(shí)現(xiàn)
Hash TableResizable ArrayBalanced TreeLinked ListHash Table + Linked List
InterfacesSetHashSetTreeSetLinkedHashSet
ListArrayList
5.9- java.util.ArrayList
ArrayList擁有充分的List接口的功能。此外,它允許訪問隨機(jī)元素,由于繼承了RandomAccess。
它基本上類似于Vector類。然而,雖然Vector方法是同步的,這些ArrayList都沒有。 因此ArrayList適合于單線程的應(yīng)用程序。
ArrayListDemo.java
package com.yiibai.tutorial.javacollection.list;
import java.util.ArrayList;
public class ArrayListDemo {
? public static void main(String[] args) {
? ? ? // Create an ArrayList object that contains the element Integer.
? ? ? ArrayList list = new ArrayList(10);
? ? ? // Add elements
? ? ? list.add(123);
? ? ? list.add(245);
? ? ? list.add(new Integer(345));
? ? ? // ArrayList allow add null elements.
? ? ? // (Feature of List)
? ? ? list.add(null);
? ? ? // Print out the number of elements in this list.
? ? ? System.out.println("Size:" + list.size());// =4
? ? ? // Random access to elements of index 1.
? ? ? Integer i = list.get(1);
? ? ? System.out.println("Element index 1 =" + i);// =245
? ? ? Integer newInt = 1000;
? ? ? // Replaces the element at the specified position
? ? ? // in this list with the specified element.
? ? ? Integer old = list.set(1, newInt);
? ? ? //
? ? ? System.out.println("Old value:" +old);// =245 .
? ? ? System.out.println("New value:" + list.get(1));// =1000 .
? }
}
運(yùn)行實(shí)例的結(jié)果:
Size:4
Element index 1 =245
Old value:245
New value:1000
5.10- java.util.Vector
Vector是一個(gè)類,其功能類似于ArrayList。?所不同的是Vector?的方法同步,而ArrayList的方法不同步。
Vector?的方法是同步的,所以在多線程應(yīng)用程序它運(yùn)行良好。
Vector有一些是1.0版繼承附加的方法,在Java提到集合框架的概念之前。
// Legacy method from 1.0, get element at index position
// Like get(index)
public E elementAt(int index)
// Method inherited from the List interface, get element at position index.
public E get(int index)
// Replaces the element at the specified position in this list with the specified element
// Return old element.
// setElementAt(int,E) like set(int,E)
public void setElementAt(int index, E element);
// Replaces the element at the specified position in this list with the specified element
// Return old element.
public E set(int index, E element)
VectorDemo.java
package com.yiibai.tutorial.javacollection.list;
import java.util.Vector;
public class VectorDemo {
? ? public static void main(String[] args) {
? ? ? ? // Create Vector object with capacity 10 (element)
? ? ? ? // Automatically increase capacity 5, if the number of elements to
? ? ? ? // overcome the current capacity.
? ? ? ? Vector v = new Vector(10, 5);
? ? ? ? v.add(123);
? ? ? ? v.add(245);
? ? ? ? v.add(new Integer(345));
? ? ? ? v.add(null);
? ? ? ? // Returns the number of elements in this vector. (Not capacity).
? ? ? ? System.out.println("Size:" + v.size());// =4
? ? ? ? // Get element at index 1
? ? ? ? // (like method get(int))
? ? ? ? Integer i = v.elementAt(1);
? ? ? ? System.out.println("v.elementAt(1)=" + i);// 245
? ? ? ? // Method này tr? v? ph?n t? c?.
? ? ? ? // Set element at index 1,
? ? ? ? // and return old element at index 1.
? ? ? ? v.setElementAt(1, 1000);
? ? ? ? //
? ? ? ? System.out.println("New value:" + v.get(1));// =1000 .
? ? }
}
運(yùn)行示例的結(jié)果:
5.11- java.util.SortedSet
SortedSet是Set接口的子類型的接口,它充滿著Set的功能。SortedSet是具有一個(gè)有組織的Set類,加入到集合類新元素自動(dòng)放在一個(gè)合適的位置,以確保集合仍在排列(升序或降序)。
因此,SortedSet的元素必須彼此進(jìn)行比較,并且它們必須是java.lang.Comparable的對(duì)象(可以是comparable)。??
如果添加不是Comparable的元素到SortedSet對(duì)象,會(huì)得到一個(gè)異常。
類實(shí)現(xiàn)?SortedSet:??TreeSet.
考慮球員(Player)類,包括以下信息:姓名,金牌數(shù),銀牌數(shù),銅牌數(shù)。
球員(Player)可以相互根據(jù)原理進(jìn)行比較:
誰(shuí)擁有更多的金牌則排名會(huì)更高
如果兩個(gè)人有相同數(shù)量的金牌,誰(shuí)擁有更多的銀牌則排名就越靠前
如果兩個(gè)人有相同數(shù)量的金牌和銀牌,誰(shuí)擁有更多銅牌則排名將更高
其他的則被視為是同等級(jí)的
Player類將實(shí)現(xiàn) java.lang.Comparable 的接口
Player.java
package com.yiibai.tutorial.javacollection.sortedset;
public class Player implements Comparable {
? ? private String name;
? ? private int goldMedal;
? ? private int silverMedal;
? ? private int bronzeMedal;
? ? public Player(String name, int goldMedal, int silverMedal, int bronzeMedal) {
? ? ? ? this.name = name;
? ? ? ? this.goldMedal = goldMedal;
? ? ? ? this.silverMedal = silverMedal;
? ? ? ? this.bronzeMedal = bronzeMedal;
? ? }
? ? // Compare this player with other player
? ? // Return < 0 means this player < other
? ? // Return > 0 means this player > other
? ? // Return 0 means this player = other
? ? @Override
? ? public int compareTo(Player other) {
? ? ? ? // Compare the number of gold medals.
? ? ? ? int value = this.goldMedal - other.goldMedal;
? ? ? ? if (value != 0) {
? ? ? ? ? ? return value;
? ? ? ? }
? ? ? ? // Compare the number of silver medals.
? ? ? ? value = this.silverMedal - other.silverMedal;
? ? ? ? if (value != 0) {
? ? ? ? ? ? return value;
? ? ? ? }
? ? ? ? // Compare the number of bronze medals.
? ? ? ? value = this.bronzeMedal - other.bronzeMedal;
? ? ? ? return value;
? ? }
? ? @Override
? ? public String toString() {
? ? ? ? return "[" + this.name + ", Gold: " + this.goldMedal + ", Silver: " + this.silverMedal + ", Bronze: "
? ? ? ? ? ? ? ? + this.bronzeMedal + "]";
? ? }
}
SortedSetDemo.java
package com.yiibai.tutorial.javacollection.sortedset;
import java.util.SortedSet;
import java.util.TreeSet;
public class SortedSetDemo {
? ? public static void main(String[] args) {
? ? ? ? // Create SortedSet object.
? ? ? ? SortedSet players = new TreeSet();
? ? ? ? Player tom = new Player("Tom", 1, 3, 5);
? ? ? ? Player jerry = new Player("Jerry", 3, 1, 3);
? ? ? ? Player donald = new Player("Donal", 2, 10, 0);
? ? ? ? // Add element to set
? ? ? ? // They will automatically be sorted (Ascending).
? ? ? ? players.add(tom);
? ? ? ? players.add(jerry);
? ? ? ? players.add(donald);
? ? ? ? // Print out elements
? ? ? ? for(Player player : players) {
? ? ? ? ? ? System.out.println("Player: "+ player);
? ? ? ? }
? ? }
}
運(yùn)行?SortedSetDemo?實(shí)例的結(jié)果如下:
Player: [Tom, Gold: 1, Silver: 3, Bronze: 5]
Player: [Donal, Gold: 2, Silver: 10, Bronze: 0]
Player: [Jerry, Gold: 3, Silver: 1, Bronze: 3]
6- Map組
6.1-?映射組接口
由 java.util.Map 接口主導(dǎo) Map 組。該接口有2個(gè)子接口分別是java.util.SortedMap和java.util.concurrent.ConcurrentMap。?ConcurrentMap不屬于java.util包,它是從Java版本1.5引入的,我們不打算在教程講解它。?Map組特點(diǎn)是存儲(chǔ)鍵/值對(duì)的數(shù)據(jù)。
6.2-?在Map組中的類
6.3- java.util.Map接口
SN方法及描述
1void clear( )
調(diào)用移除Map中的所有鍵/值對(duì)(可選操作)
2boolean containsKey(Object k)
如果調(diào)用映射包含一個(gè)鍵k,則返回true,否則返回false
3boolean containsValue(Object v)
如果Map包含一個(gè)值v,則返回true。否則,返回false
4Set> entrySet( )
返回包含在映射中條目的集合。集合中包含 Map.Entry 類型的對(duì)象。這種方法提供調(diào)用映射設(shè)置視圖
5boolean equals(Object obj)
如果 obj 是一個(gè)在 Map 中包含的相同項(xiàng)目,則返回true。否則,返回false
6Object get(K k)
返回與k關(guān)聯(lián)的值
7int hashCode( )
返回調(diào)用映射的哈希碼
8boolean isEmpty( )
返回true如果調(diào)用映射為空。否則,返回false
9Set keySet( )
返回包含調(diào)用Map中的鍵的集合(Set),該方法提供了在調(diào)用映射中的鍵的一組視圖
10Object put(K k, V v)
放入調(diào)用映射一個(gè)條目,覆蓋先前與鍵相關(guān)聯(lián)的值。鍵和值分別為K和V。如果該鍵不存在,則返回null。否則關(guān)聯(lián)到鍵先前的值被返回(可選操作)
11void putAll(Map m)
把?m?中的全部項(xiàng)目放入此Map(可選操作)
12Object remove(Object k)
刪除其鍵等于k處的項(xiàng)(可選操作)
13int size( )
返回映射的鍵/值對(duì)的數(shù)量
14Collection values( )
返回包含映射中值的集合,該方法提供了在映射中的值的集合視圖。
可選方法(可選操作),可以被支持它的實(shí)現(xiàn)類或沒有,如果不支持,它會(huì)拋出 UnsupportedOperationException 異常:
import java.util.Collection;
import java.util.Map;
import java.util.Set;
public class MyMap implements Map{
? .....
? ? // If you call this method, an exception will be thrown (unconditional).
? ? @Override
? ? public void clear() {
? ? ? ? throw new java.lang.UnsupportedOperationException();? ? ? ?
? ? }?
}?
因此,MyMap類不支持clear()方法的真正含意。如果用戶有意使用 MyMap 中的這個(gè)方法,會(huì)收到一個(gè)異常。
MapDemo.java
package com.yiibai.tutorial.javacollection.map;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapDemo {
? ? public static void main(String[] args) {
? ? ? ? Map map = new HashMap();
? ? ? ? map.put("01000005", "Tom");
? ? ? ? map.put("01000002", "Jerry");
? ? ? ? map.put("01000003", "Tom");
? ? ? ? map.put("01000004", "Donald");
? ? ? ? // Get a set view of the keys contained in this map
? ? ? ? // This collection is not sorted
? ? ? ? Set phones = map.keySet();
? ? ? ? for (String phone : phones) {
? ? ? ? ? ? System.out.println("Phone: " + phone + " : " + map.get(phone));
? ? ? ? }
? ? }
}
運(yùn)行實(shí)例的結(jié)果如下:
Phone: 01000004 : Donald
Phone: 01000003 : Tom
Phone: 01000005 : Tom
Phone: 01000002 : Jerry
您可以通過Map.Entry訪問映射的數(shù)據(jù),見下圖:
MapEntryDemo.java
package com.yiibai.tutorial.javacollection.map;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class MapEntryDemo {
? ? public static void main(String[] args) {
? ? ? ? Map map = new HashMap();
? ? ? ? map.put("01000005", "Tom");
? ? ? ? map.put("01000002", "Jerry");
? ? ? ? map.put("01000003", "Tom");
? ? ? ? map.put("01000004", "Donald");
? ? ? ? // Get set of entries
? ? ? ? // This entry may not sort by key.
? ? ? ? Set> entries = map.entrySet();
? ? ? ? for (Entry entry : entries) {
? ? ? ? ? ? System.out.println("Phone: " + entry.getKey() + " : " + entry.getValue());
? ? ? ? }
? ? }
}
運(yùn)行實(shí)例的結(jié)果如下:
Phone: 01000004 : Donald
Phone: 01000003 : Tom
Phone: 01000005 : Tom
Phone: 01000002 : Jerry
6.4- java.util.SortedMap接口
SortedMap是 Map 的子接口。它確保鍵/值對(duì)根據(jù)鍵以升序排列。
在java.util中只有一個(gè)類實(shí)現(xiàn) SortedMap 接口,它就是TreeMap。
SortedMap 類的方法:
SN描述及方法
1Comparator comparator( )
返回調(diào)用Map的比較器(comparator),如果自然順序用于調(diào)用映射,則返回null
2Object firstKey( )
返回調(diào)用映射的第一個(gè)鍵
3SortedMap headMap(Object end)
返回映射條目與小于 end 鍵的有序映射
4Object lastKey( )
返回調(diào)用映射的最后一個(gè)鍵
5SortedMap subMap(Object start, Object end)
返回一個(gè)包含鍵大于或等于start?并小于?end 的那些條目的映射
6SortedMap tailMap(Object start)
返回包含鍵大于或等于?start?的那些條目的映射.
SortedMapDemo.java
package com.yiibai.tutorial.javacollection.sortedmap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class SortedMapDemo {
? ? public static void main(String[] args) {
? ? ? ? Map map = new TreeMap();
? ? ? ? map.put("01000005", "Tom");
? ? ? ? map.put("01000002", "Jerry");
? ? ? ? map.put("01000003", "Tom");
? ? ? ? map.put("01000004", "Donald");
? ? ? ? // This set has been sorted in ascending
? ? ? ? Set keys = map.keySet();
? ? ? ? for (String key : keys) {
? ? ? ? ? ? System.out.println("Phone: " + key);
? ? ? ? }
? ? ? ? System.out.println("-----");
? ? ? ? // This set has been sorted in ascending
? ? ? ? Set> entries = map.entrySet();
? ? ? ? for (Map.Entry entry : entries) {
? ? ? ? ? ? System.out.println("Phone: " + entry.getKey());
? ? ? ? }
? ? }
}
運(yùn)行實(shí)例的結(jié)果如下:
Phone: 01000002
Phone: 01000003
Phone: 01000004
Phone: 01000005
-----
Phone: 01000002
Phone: 01000003
Phone: 01000004
Phone: 01000005