Java容器使用总结-阿里云开发者社区

开发者社区> 开发与运维> 正文
登录阅读全文

Java容器使用总结

简介:

Collection 

List 
│├LinkedList 
│├ArrayList 
│└Vector 

│└Stack 

Queue

│├Deque

│└LinkedList

Set 
  ├SortedSet 
  ├TreeSet
  └HashSet

Map 
├Hashtable 
├HashMap 
└WeakHashMap


Collection接口 
Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的元素(Elements)。一些 Collection允许相同的元素而另一些不行。一些能排序而另一些不行。Java SDK不提供直接继承自Collection的类,Java SDK提供的类都是继承自Collection的“子接口”如List和Set。 
所有实现Collection接口的类都必须提供两个标准的构造函数:无参数的构造函数用于创建一个空的Collection,有一个 Collection参数的构造函数用于创建一个新的Collection,这个新的Collection与传入的Collection有相同的元素。后一个构造函数允许用户复制一个Collection。 
如何遍历Collection中的每一个元素?不论Collection的实际类型如何,它都支持一个iterator()的方法,该方法返回一个迭代子,使用该迭代子即可逐一访问Collection中每一个元素。典型的用法如下: 
Iterator it = collection.iterator(); // 获得一个迭代子 
while(it.hasNext()) { 
Object obj = it.next(); // 得到下一个元素 

由Collection接口派生的两个接口是List和Set。

List接口 
List是有序的Collection,使用此接口能够精确的控制每个元素插入的位置。用户能够使用索引(元素在List中的位置,类似于数组下标)来访问List中的元素,这类似于Java的数组。 
和下面要提到的Set不同,List允许有相同的元素。 
除了具有Collection接口必备的iterator()方法外,List还提供一个listIterator()方法,返回一个 ListIterator接口,和标准的Iterator接口相比,ListIterator多了一些add()之类的方法,允许添加,删除,设定元素,还能向前或向后遍历。 
实现List接口的常用类有LinkedList,ArrayList,Vector和Stack。

LinkedList类 
LinkedList实现了List接口,允许null元素。此外LinkedList提供额外的get,remove,insert方法在 LinkedList的首部或尾部。这些操作使LinkedList可被用作堆栈(stack),队列(queue)或双向队列(deque)。 
注意LinkedList没有同步方法。如果多个线程同时访问一个List,则必须自己实现访问同步。一种解决方法是在创建List时构造一个同步的List: 
List list = Collections.synchronizedList(new LinkedList(...));

ArrayList类 
ArrayList实现了可变大小的数组。它允许所有元素,包括null。ArrayList没有同步。 
size,isEmpty,get,set方法运行时间为常数。但是add方法开销为分摊的常数,添加n个元素需要O(n)的时间。其他的方法运行时间为线性。 
每个ArrayList实例都有一个容量(Capacity),即用于存储元素的数组的大小。这个容量可随着不断添加新元素而自动增加,但是增长算法并没有定义。当需要插入大量元素时,在插入前可以调用ensureCapacity方法来增加ArrayList的容量以提高插入效率。 
和LinkedList一样,ArrayList也是非同步的(unsynchronized)。

Vector类 
Vector非常类似ArrayList,但是Vector是同步的。由Vector创建的Iterator,虽然和ArrayList创建的 Iterator是同一接口,但是,因为Vector是同步的,当一个Iterator被创建而且正在被使用,另一个线程改变了Vector的状态(例如,添加或删除了一些元素),这时调用Iterator的方法时将抛出ConcurrentModificationException,因此必须捕获该异常。

Stack 类 
Stack继承自Vector,实现一个后进先出的堆栈。Stack提供5个额外的方法使得Vector得以被当作堆栈使用。基本的push和pop 方法,还有peek方法得到栈顶的元素,empty方法测试堆栈是否为空,search方法检测一个元素在堆栈中的位置。Stack刚创建后是空栈。

Set接口 
Set是一种不包含重复的元素的Collection,即任意的两个元素e1和e2都有e1.equals(e2)=false,Set最多有一个null元素。 
很明显,Set的构造函数有一个约束条件,传入的Collection参数不能包含重复的元素。 
请注意:必须小心操作可变对象(Mutable Object)。如果一个Set中的可变元素改变了自身状态导致Object.equals(Object)=true将导致一些问题。

Map接口 
请注意,Map没有继承Collection接口,Map提供key到value的映射。一个Map中不能包含相同的key,每个key只能映射一个 value。Map接口提供3种集合的视图,Map的内容可以被当作一组key集合,一组value集合,或者一组key-value映射。

Hashtable类 
Hashtable继承Map接口,实现一个key-value映射的哈希表。任何非空(non-null)的对象都可作为key或者value。 
添加数据使用put(key, value),取出数据使用get(key),这两个基本操作的时间开销为常数。 
Hashtable通过initial capacity和load factor两个参数调整性能。通常缺省的load factor 0.75较好地实现了时间和空间的均衡。增大load factor可以节省空间但相应的查找时间将增大,这会影响像get和put这样的操作。 
使用Hashtable的简单示例如下,将1,2,3放到Hashtable中,他们的key分别是”one”,”two”,”three”: 
Hashtable numbers = new Hashtable(); 
numbers.put(“one”, new Integer(1)); 
numbers.put(“two”, new Integer(2)); 
numbers.put(“three”, new Integer(3)); 
要取出一个数,比如2,用相应的key: 
Integer n = (Integer)numbers.get(“two”); 
System.out.println(“two = ” + n); 
由于作为key的对象将通过计算其散列函数来确定与之对应的value的位置,因此任何作为key的对象都必须实现hashCode和equals方法。hashCode和equals方法继承自根类Object,如果你用自定义的类当作key的话,要相当小心,按照散列函数的定义,如果两个对象相同,即obj1.equals(obj2)=true,则它们的hashCode必须相同,但如果两个对象不同,则它们的hashCode不一定不同,如果两个不同对象的hashCode相同,这种现象称为冲突,冲突会导致操作哈希表的时间开销增大,所以尽量定义好的hashCode()方法,能加快哈希表的操作。 
如果相同的对象有不同的hashCode,对哈希表的操作会出现意想不到的结果(期待的get方法返回null),要避免这种问题,只需要牢记一条:要同时复写equals方法和hashCode方法,而不要只写其中一个。 
Hashtable是同步的。

HashMap类 
HashMap和Hashtable类似,不同之处在于HashMap是非同步的,并且允许null,即null value和null key。,但是将HashMap视为Collection时(values()方法可返回Collection),其迭代子操作时间开销和HashMap 的容量成比例。因此,如果迭代操作的性能相当重要的话,不要将HashMap的初始化容量设得过高,或者load factor过低。

WeakHashMap类 
WeakHashMap是一种改进的HashMap,它对key实行“弱引用”,如果一个key不再被外部所引用,那么该key可以被GC回收。

总结 
如果涉及到堆栈,队列等操作,应该考虑用List,对于需要快速插入,删除元素,应该使用LinkedList,如果需要快速随机访问元素,应该使用ArrayList。 
如果程序在单线程环境中,或者访问仅仅在一个线程中进行,考虑非同步的类,其效率较高,如果多个线程可能同时操作一个类,应该使用同步的类。 
要特别注意对哈希表的操作,作为key的对象要正确复写equals和hashCode方法。 
尽量返回接口而非实际的类型,如返回List而非ArrayList,这样如果以后需要将ArrayList换成LinkedList时,客户端代码不用改变。这就是针对抽象编程。


比较
①Vector和ArrayList
Vector的方法都是同步的(Synchronized),是线程安全的(thread-safe),而ArrayList的方法不是,由于线程的同步必然要影响性能,因此,ArrayList的性能比Vector好。 
当Vector或ArrayList中的元素超过它的初始大小时,Vector会将它的容量翻倍,而ArrayList只增加50%的大小,这样,ArrayList就有利于节约内存空间。 
②Hashtable和HashMap   
它们的性能方面的比较类似 Vector和ArrayList,比如Hashtable的方法是同步的,而HashMap的不是。 
③ArrayList和LinkedList   
对 于处理一列数据项,Java提供了两个类ArrayList和LinkedList,ArrayList的内部实现是基于内部数组Object[],所以 从概念上讲,它更象数组,但LinkedList的内部实现是基于一组连接的记录,所以,它更象一个链表结构,所以,它们在性能上有很大的差别。   

List用法
List<ElemType> L = new ArrayList<ElemType>();
Modifier and Type Method and Description
boolean add(E e)
Appends the specified element to the end of this list (optional operation).
void add(int index, E element)
Inserts the specified element at the specified position in this list (optional operation).
boolean addAll(Collection<? extends E> c)
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation).
boolean addAll(int index, Collection<? extends E> c)
Inserts all of the elements in the specified collection into this list at the specified position (optional operation).
void clear()
Removes all of the elements from this list (optional operation).
boolean contains(Object o)
Returns true if this list contains the specified element.
boolean containsAll(Collection<?> c)
Returns true if this list contains all of the elements of the specified collection.
boolean equals(Object o)
Compares the specified object with this list for equality.
E get(int index)
Returns the element at the specified position in this list.
int hashCode()
Returns the hash code value for this list.
int indexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
boolean isEmpty()
Returns true if this list contains no elements.
Iterator<E> iterator()
Returns an iterator over the elements in this list in proper sequence.
int lastIndexOf(Object o)
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
ListIterator<E> listIterator()
Returns a list iterator over the elements in this list (in proper sequence).
ListIterator<E> listIterator(int index)
Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
E remove(int index)
Removes the element at the specified position in this list (optional operation).
boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present (optional operation).
boolean removeAll(Collection<?> c)
Removes from this list all of its elements that are contained in the specified collection (optional operation).
boolean retainAll(Collection<?> c)
Retains only the elements in this list that are contained in the specified collection (optional operation).
E set(int index, E element)
Replaces the element at the specified position in this list with the specified element (optional operation).
int size()
Returns the number of elements in this list.
List<E> subList(int fromIndex, int toIndex)
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
Object[] toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[] toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

Set用法
Set<ElemType> S = new HashSet<ElemType>();
Modifier and Type Method and Description
boolean add(E e)
Adds the specified element to this set if it is not already present (optional operation).
boolean addAll(Collection<? extends E> c)
Adds all of the elements in the specified collection to this set if they're not already present (optional operation).
void clear()
Removes all of the elements from this set (optional operation).
boolean contains(Object o)
Returns true if this set contains the specified element.
boolean containsAll(Collection<?> c)
Returns true if this set contains all of the elements of the specified collection.
boolean equals(Object o)
Compares the specified object with this set for equality.
int hashCode()
Returns the hash code value for this set.
boolean isEmpty()
Returns true if this set contains no elements.
Iterator<E> iterator()
Returns an iterator over the elements in this set.
boolean remove(Object o)
Removes the specified element from this set if it is present (optional operation).
boolean removeAll(Collection<?> c)
Removes from this set all of its elements that are contained in the specified collection (optional operation).
boolean retainAll(Collection<?> c)
Retains only the elements in this set that are contained in the specified collection (optional operation).
int size()
Returns the number of elements in this set (its cardinality).
Object[] toArray()
Returns an array containing all of the elements in this set.
<T> T[] toArray(T[] a)
Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Iterator用法:
List<Integer> L = new ArrayList<Integer>();
Iterator<Integer> i = L.iterator();
Modifier and Type Method and Description
boolean hasNext()
Returns true if the iteration has more elements.
E next()
Returns the next element in the iteration.
void remove()
Removes from the underlying collection the last element returned by this iterator (optional operation).

ListIterator用法:
List<Integer> L = new ArrayList<Integer>();
ListIterator<Integer> i = L.listIterator(0);
Modifier and Type Method and Description
void add(E e)
Inserts the specified element into the list (optional operation).
boolean hasNext()
Returns true if this list iterator has more elements when traversing the list in the forward direction.
boolean hasPrevious()
Returns true if this list iterator has more elements when traversing the list in the reverse direction.
E next()
Returns the next element in the list and advances the cursor position.
int nextIndex()
Returns the index of the element that would be returned by a subsequent call tonext().
E previous()
Returns the previous element in the list and moves the cursor position backwards.
int previousIndex()
Returns the index of the element that would be returned by a subsequent call toprevious().
void remove()
Removes from the list the last element that was returned by next() or previous() (optional operation).
void set(E e)
Replaces the last element returned by next() or previous() with the specified element (optional operation).
List和数组互相转化:
Integer nums1[] = {1,2,3,4,5};
Integer nums2[] = new Integer[4];
//复制数组
System.arraycopy(nums1, 1, nums2, 0, 4);
//数组转List
List<Integer> L = new ArrayList<Integer>();
L = Arrays.asList(nums2);
//List转数组
Integer nums3[] = L.toArray(new Integer[0]);

Map用法:
Map<String, Integer> m = new HashMap<String, Integer>();
Modifier and Type Method and Description
void clear()
Removes all of the mappings from this map (optional operation).
boolean containsKey(Object key)
Returns true if this map contains a mapping for the specified key.
boolean containsValue(Object value)
Returns true if this map maps one or more keys to the specified value.
Set<Map.Entry<K,V>> entrySet()
Returns a Set view of the mappings contained in this map.
boolean equals(Object o)
Compares the specified object with this map for equality.
V get(Object key)
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
int hashCode()
Returns the hash code value for this map.
boolean isEmpty()
Returns true if this map contains no key-value mappings.
Set<K> keySet()
Returns a Set view of the keys contained in this map.
V put(K key, V value)
Associates the specified value with the specified key in this map (optional operation).
void putAll(Map<? extends K,? extends V> m)
Copies all of the mappings from the specified map to this map (optional operation).
V remove(Object key)
Removes the mapping for a key from this map if it is present (optional operation).
int size()
Returns the number of key-value mappings in this map.
Collection<V> values()
Returns a Collection view of the values contained in this map.

Vector用法:
Modifier and Type Method and Description
boolean add(E e)
Appends the specified element to the end of this Vector.
void add(int index, E element)
Inserts the specified element at the specified position in this Vector.
boolean addAll(Collection<? extends E> c)
Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified Collection's Iterator.
boolean addAll(int index, Collection<? extends E> c)
Inserts all of the elements in the specified Collection into this Vector at the specified position.
void addElement(E obj)
Adds the specified component to the end of this vector, increasing its size by one.
int capacity()
Returns the current capacity of this vector.
void clear()
Removes all of the elements from this Vector.
Object clone()
Returns a clone of this vector.
boolean contains(Object o)
Returns true if this vector contains the specified element.
boolean containsAll(Collection<?> c)
Returns true if this Vector contains all of the elements in the specified Collection.
void copyInto(Object[] anArray)
Copies the components of this vector into the specified array.
E elementAt(int index)
Returns the component at the specified index.
Enumeration<E> elements()
Returns an enumeration of the components of this vector.
void ensureCapacity(int minCapacity)
Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.
boolean equals(Object o)
Compares the specified Object with this Vector for equality.
E firstElement()
Returns the first component (the item at index 0) of this vector.
E get(int index)
Returns the element at the specified position in this Vector.
int hashCode()
Returns the hash code value for this Vector.
int indexOf(Object o)
Returns the index of the first occurrence of the specified element in this vector, or -1 if this vector does not contain the element.
int indexOf(Object o, int index)
Returns the index of the first occurrence of the specified element in this vector, searching forwards from index, or returns -1 if the element is not found.
void insertElementAt(E obj, int index)
Inserts the specified object as a component in this vector at the specified index.
boolean isEmpty()
Tests if this vector has no components.
Iterator<E> iterator()
Returns an iterator over the elements in this list in proper sequence.
E lastElement()
Returns the last component of the vector.
int lastIndexOf(Object o)
Returns the index of the last occurrence of the specified element in this vector, or -1 if this vector does not contain the element.
int lastIndexOf(Object o, int index)
Returns the index of the last occurrence of the specified element in this vector, searching backwards from index, or returns -1 if the element is not found.
ListIterator<E> listIterator()
Returns a list iterator over the elements in this list (in proper sequence).
ListIterator<E> listIterator(int index)
Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
E remove(int index)
Removes the element at the specified position in this Vector.
boolean remove(Object o)
Removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged.
boolean removeAll(Collection<?> c)
Removes from this Vector all of its elements that are contained in the specified Collection.
void removeAllElements()
Removes all components from this vector and sets its size to zero.
boolean removeElement(Object obj)
Removes the first (lowest-indexed) occurrence of the argument from this vector.
void removeElementAt(int index)
Deletes the component at the specified index.
protected void removeRange(int fromIndex, int toIndex)
Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
boolean retainAll(Collection<?> c)
Retains only the elements in this Vector that are contained in the specified Collection.
E set(int index, E element)
Replaces the element at the specified position in this Vector with the specified element.
void setElementAt(E obj, int index)
Sets the component at the specified index of this vector to be the specified object.
void setSize(int newSize)
Sets the size of this vector.
int size()
Returns the number of components in this vector.
List<E> subList(int fromIndex, int toIndex)
Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.
Object[] toArray()
Returns an array containing all of the elements in this Vector in the correct order.
<T> T[] toArray(T[] a)
Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array.
String toString()
Returns a string representation of this Vector, containing the String representation of each element.
void trimToSize()
Trims the capacity of this vector to be the vector's current size.

Stack用法:
Modifier and Type Method and Description
boolean empty()
Tests if this stack is empty.
E peek()
Looks at the object at the top of this stack without removing it from the stack.
E pop()
Removes the object at the top of this stack and returns that object as the value of this function.
E push(E item)
Pushes an item onto the top of this stack.
int search(Object o)
Returns the 1-based position where an object is on this stack.

Queue用法:
Modifier and Type Method and Description
boolean add(E e)
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
E element()
Retrieves, but does not remove, the head of this queue.
boolean offer(E e)
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
E peek()
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
E poll()
Retrieves and removes the head of this queue, or returns null if this queue is empty.
E remove()
Retrieves and removes the head of this queue.






参考资料:
1 http://www.cnblogs.com/vamei/archive/2013/04/15/3000913.html
2 http://www.cnblogs.com/sunliming/archive/2011/04/05/2005957.html
3 Java帮助文档

转载:http://blog.csdn.net/foreverling/article/details/46548587

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

其他文章