Java類集引出
類集實際上就屬於動態對象數組,在實際開發之中,數組的使用出現的機率並不高,因爲數組本身有一個最大的缺陷:數組長度是固定的。由於此問題的存在,從JDK1.2開始,Java爲了解決這種數組長度問題,提供了動態的對象數組實現框架–Java類集框架。
Java集合類框架實際上就是java針對於數據結構的一種實現。實際上鍊表的實現就是參考Java集合類實現的。
Collection
在Java的類集裏面(java.util包)提供了兩個最爲核心的接口:Collection
、Map
接口。其中Collection接口的操作形式與鏈表的操作形式類似,每一次進行數據操作的時候只能夠對單個對象進行處理;Map接口針對鍵值對對象處理。
Collection接口的定義如下:
public interface Collection<E> extends Iterable<E>
從JDK1.5開始發現Collection接口上追加有泛型應用,這樣的直接好處就是可以避免ClassCastException
,裏面的所有數據的保存類型應該是相同的。在JDK1.5之前Iterable
接口中的iterator()
方法是直接在Collection接口中定義的。此接口的常用方法有如下幾個:
在開發之中如果按照使用頻率來講:add()
、iterator()
方法用到的最多。
add():向集合中添加元素
iterator():取得集合的迭代器(遍歷集合的工具)
需要說明的一點是,我們很少會直接使用 Collection接口,Collection接口只是一個存儲數據的標準,並不能區分存儲類型。例如:要存放的數據需要區分重複與不重複。在實際開發之中,往往會考慮使用Collection接口的子接口:List(允許數據重複)、Set(不允許數據重複)。
List接口
List接口概述
首先來觀察List接口中提供的方法,在這個接口中有兩個重要的擴充方法 :
public E get(int index):根據索引取得數據
public E set(int index,E element):根據指定索引修改相應元素
List子接口與Collection接口相比最大的特點在於其有一個get()
方法,可以根據索引取得內容。由於List本身還是接口,要想取得接口的實例化對象,就必須有子類,在List接口下有三個常用子類:ArrayList
、Vector
、LinkedList
。
ArrayList子類
- 接口中要保存自定義類對象,自定義類必須覆寫
equals()
。類集contains()、remove()等方法需要調用equals()來判斷元素是否相等。
package www.bit.Collection;
import java.util.ArrayList;
import java.util.List;
class Person {
private String name;
private int age;
@Override
public boolean equals(Object obj) {
if (obj == this){
return true;
}
if (obj == null){
return false;
}
if (!(obj instanceof Person)){
return false;
}
Person person = (Person)obj;
return this.age == person.age && person.name.equals(this.name);
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Test {
public static void main(String[] args){
List<Person> list = new ArrayList<>();
Person person1 = new Person("周潤發",50);
Person person2 = new Person("周星馳",40);
Person person3 = new Person("成龍",45);
list.add(person1);
list.add(person2);
list.add(person3);
System.out.println(list.contains(new Person("周星馳",40)));
System.out.println(list.size());
}
}
- 底層實現是一個對象數組,聲明一個ArrayList對象時,長度爲0。當數組長度不夠用時,擴容策略爲變爲原來數組的1.5倍。
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
- 對集合的增刪改查都是異步處理,性能較高,線程不安全。
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
Vector
- 底層實現是一個對象數組,聲明一個Vector對象時,初始化對象數組長度爲10。當數組長度不夠用時,擴容策略變爲原來的2倍。
/**
* Constructs an empty vector so that its internal data array
* has size {@code 10} and its standard capacity increment is
* zero.
*/
public Vector() {
this(10);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
- 對集合的修改都採用同步處理(直接在方法上使用內建鎖),性能較低,線程安全。
/**
* Appends the specified element to the end of this Vector.
*
* @param e element to be appended to this Vector
* @return {@code true} (as specified by {@link Collection#add})
* @since 1.2
*/
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
請解釋ArrayList
與Vector
的區別:
-
產生版本:Vector是JDK1.0產生,ArrayList是JDK1.2產生
-
線程安全:Vector採用在方法添加synchronized來保證線程安全,性能較低;ArrayList採用異步處理,性能較高,線程不安全
-
初始化以及擴容策略:Vector對象產生時就初始化大小爲10,當數組不夠用時,擴容爲原數組的2倍;ArrayList使用懶加載策略,在第一次添加元素時才初始化數組大小,當數組不夠用時,擴容爲原數組的1.5倍。
LinkList
- 基於鏈表實現的動態數組
/**
* Links e as first element.
*/
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
/**
* Inserts the specified element at the specified position in this list.
* Shifts the element currently at that position (if any) and any
* subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
/**
* Links e as last element.
*/
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
- ArrayList封裝的是數組;LinkedList封裝的是鏈表。ArrayList時間複雜度爲1,而LinkedList的複雜度爲n
Set集合接口
Set接口與List接口最大的不同在於Set接口中的內容是不允許重複的。同時需要注意的是,Set接口並沒有對 Collection接口進行擴充,而List對Collection進行了擴充。因此,在Set接口中沒有get()
方法。
在Set子接口中有兩個常用子類:HashSet
(無序存儲)、TreeSet
(有序存儲)
HashSet無序存儲
-
底層基於哈希表
-
不允許元素重複並且無序存儲(根據哈希碼保存元素),允許存放null
package www.bit.Collection;
import java.util.HashSet;
import java.util.Set;
public class SetTest {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("SetTest");
set.add("hello");
set.add("China");
set.add(null);
set.add("hello");
set.add("world");
set.add(null);
System.out.println(set);
}
}
運行結果:
[null, world, China, hello, SetTest]
Process finished with exit code 0
TreeSet有序存儲
-
底層基於紅黑樹
-
不允許元素重複並且按照升序排序,不允許存放null
package www.bit.Collection;
import java.util.Set;
import java.util.TreeSet;
public class SetTest {
public static void main(String[] args) {
Set<String> set = new TreeSet<>();
set.add("Banana");
set.add("Pear");
set.add("Apple");
set.add("Watermelon");
set.add("Apple");
System.out.println(set);
}
}
運行結果:
[Apple, Banana, Pear, Watermelon]
Process finished with exit code 0