Several Java containers you must Know (collection Class)

Source: Internet
Author: User

first, the basic concept

The purpose of the Java Container Class library is to "hold objects" and divide them into two different concepts:

1) Collection: A sequence of independent elements that obey one or more rules. the list must save the element in the order in which it was inserted, and set cannot have duplicate elements. The queue determines the order in which objects are produced, usually in the same order in which they are inserted, according to the queuing rules.
2) Map: A pair of "key-value pairs" objects that allow you to use keys to look up values.

| Collection
| ├list
| │-├linkedlist
| │-├arraylist
| │-└vector
| │└stack
| ├set
| │├hashset
| │├treeset
| │└linkedset
|
| Map
├hashtable
├hashmap
└weakhashmap

Note: 1, Java.util.Collection is a collection interface. it provides a common interface method for basic manipulation of collection objects. The collection interface has many specific implementations in the Java class Library. The meaning of the collection interface is to provide a maximum unified operation for a variety of specific collections.
  2, Java.util.Collections is a packaging class. it contains a variety of static polymorphic methods related to set operations. This class cannot be instantiated, just like a tool class that serves the Java collection framework.

second, collection set interface

Collection is the most basic set interface, and a collection represents a set of object, the collection element (Elements). Some collection allow the same elements while others do not. Some can sort and others can't. The Java SDK does not provide classes that inherit directly from collection, and the Java SDK provides classes that inherit from collection, such as list and set.

主要方法:boolean add(Object o)添加对象到集合boolean remove(Object o)删除指定的对象int size()返回当前集合中元素的数量boolean contains(Object o)查找集合中是否有指定的对象boolean isEmpty()判断集合是否为空Iterator iterator()返回一个迭代器boolean containsAll(Collection c)查找集合中是否有集合c中的元素boolean addAll(Collection c)将集合c中所有的元素添加给该集合void clear()删除集合中所有元素void removeAll(Collection c)从集合中删除c集合中也有的元素void retainAll(Collection c)从集合中删除集合c中不包含的元素
1. List interface

The list is an ordered collection, using this interface to precisely control where each element is inserted. The user is able to access the elements in the list using an index (where the element is positioned in the list, similar to an array subscript), similar to an array of java.
The common classes that implement the list interface are Linkedlist,arraylist,vector and stacks.

  1) LinkedList class
The LinkedList implements a list interface that allows null elements. Additionally LinkedList provides an additional Get,remove,insert method at the first or the tail of the LinkedList. These operations make the LinkedList available as a stack (stack), queue, or two-way queue (deque).

Note: LinkedList does not have a synchronization method. If multiple threads access a list at the same time, you must implement access synchronization yourself. One workaround is to construct a synchronized list:list list = collections.synchronizedlist (new LinkedList (...) when the list is created;

  2) ArrayList class
ArrayList implements a variable-size array. It allows all elements, including null. ArrayList is not synchronized. Size,isempty,get,set method run time is constant. But the Add method cost is the allocated constant, and adding n elements requires an O (n) time. Other methods run at a linear time. Each ArrayList instance has a capacity (capacity), which is the size of the array used to store the elements. This capacity automatically increases as new elements are added, but the growth algorithm is not defined. When you need to insert a large number of elements, you can call the Ensurecapacity method before inserting to increase the capacity of the ArrayList to improve insertion efficiency.

Like LinkedList, ArrayList is also unsynchronized (unsynchronized). In general the use of these two can be, because of the non-synchronous, so the efficiency is higher.
if it involves operations such as stacks, queues, and so on, you should consider using the list, for quick insertions, for deleting elements, should use LinkedList, and if you need to quickly randomly access elements, you should use ArrayList.

  3) Vector class
Vectors are very similar to ArrayList, but vectors are synchronous. The iterator created by the vector, although the same interface as the iterator created by ArrayList, but because the vector is synchronous, when a iterator is created and is being used, another thread changes the state of the vector (for example, Some elements have been added or removed, Concurrentmodificationexception will be thrown when the iterator method is called, so the exception must be caught.

  4) Stack class
Stack inherits from Vector and implements a last-in-first-out stack. The stack provides 5 additional ways to make the vector available as a stack. The basic push and pop methods, and the Peek method to get the stack top element, the empty method tests if the stack is empty, and the search method detects the position of an element on the stack. Stack has just been created as an empty stack.

2. Set interface

Set is a collection that contains no duplicate elements, that is, any two elements E1 and E2 have E1.equals (E2) =false,set have a maximum of one null element. The constructor of a set has a constraint that the passed-in collection parameter cannot contain duplicate elements.
The set container class mainly has hashset and treeset and so on.
  
  1) HashSet class
The Java.util.HashSet class implements the Java.util.Set interface.
It does not allow duplicate elements;
The order of elements in the political and political collections is not guaranteed
-a allows an element with a value of NULL, but can have at most one null element.

 Public classtesthashset{ Public Static void Main(String [] args) {HashSet h=NewHashSet (); H.add ("1st"); H.add ("2nd"); H.add (NewInteger (3)); H.add (NewDouble (4.0)); H.add ("2nd");//duplicate element, not addedH.add (NewInteger (3));//duplicate element, not addedH.add (NewDate ()); System. out. println ("Start: size="+h.size ()); Iterator It=h.iterator (); while(It.hasnext ())           {Object o=it.next (); System. out. println (o); } h.remove ("2nd"); System. out. println ("After removing elements: size="+h.size ()); System. out. println (h); }}

  2) TreeSet
TreeSet describes a variant of set-a collection of functions such as sorting, which is automatically inserted into an ordered sequence of objects by a comparison rule when the object element is added to the collection, and guarantees that the reading Uixiangxulie of the set element are arranged in ascending order.

publicclass TestTreeSet{    publicstaticvoidmain(String [] args)    {       TreeSet ts=new TreeSet();       ts.add("orange");       ts.add("apple");       ts.add("banana");       ts.add("grape");       Iterator it=ts.iterator();       while(it.hasNext())       {           String fruit=(String)it.next();           System.out.println(fruit);       }    }}
second, map set interface

Map does not inherit the collection interface, and map provides a key-to-value mapping. A map cannot contain the same key, and each key can only map one value. The map interface provides views of 3 collections, and the contents of the map can be treated as a set of key sets, a set of value collections, or a set of key-value mappings.

主要方法:booleanequals(Object o)比较对象boolean remove(Object o)删除一个对象put(Objectkey,Object value)添加key和valueHashtable类

1, Hashtable class
Hashtable inherits the map interface to implement a key-value mapped hash table. Any object that is not empty (non-null) can be either a key or a value. * * Add data using put (key, value), take out data using get (key), these two basic operations have a constant time overhead. The **hashtable adjusts performance through the initial capacity and load factor two parameters. Normally the default load factor 0.75 is a good way to achieve a balanced time and space. Increasing the load factor can save space but the corresponding lookup time will increase, which will affect operations like get and put.

Because an object that is a key will determine the position of its corresponding value by calculating its hash function, any object that is a key must implement the Hashcode and Equals methods. The hashcode and Equals methods inherit from the root class object, and if you use a custom class as key, be quite careful, as defined by the hash function, if two objects are the same, i.e. obj1.equals (OBJ2) =true, Their hashcode must be the same, but if two objects are different, their hashcode may not be different, if the hashcode of two different objects is the same, this phenomenon is called a conflict, the conflict causes the time overhead of manipulating the hash table, so define the hashcode () as much as possible. method to speed up the operation of the hash table.

If the same object has different hashcode, the operation of the hash table will have unexpected results (expecting the Get method to return null), to avoid this problem, you need to keep in mind one: to replicate both the Equals method and the Hashcode method, rather than write only one of them.

2, HashMap class
HashMap and Hashtable are similar, except that HashMap is non-synchronous and allows NULL, that is, null value and null key, but when HashMap is considered collection (values () Method can return collection), and its iterative sub-operation time overhead is proportional to the capacity of the HashMap. Therefore, if the performance of the iterative operation is quite important, do not set the initialization capacity of the hashmap too high or load factor too low.

-jdk1.0 introduces the first associated collection class HashTable, which is thread-safe . All the methods of Hashtable are synchronous.
-jdk2.0 introduces the HashMap, which provides an unsynchronized base class and a synchronized wrapper synchronizedmap. Synchronizedmap is known as a conditional thread-safe class .
The implementation of the map thread securityintroduced in the-jdk5.0util.concurrent package is Concurrenthashmap, which provides greater flexibility than synchronizedmap. Simultaneous read and write operations can be performed concurrently to

Hashtable and HashMap differences

First, the succession is different. Public class Hashtable extends Dictionary Implements Map     Public class HashMap  extends Abstractmap Implements MapSecondHashtableThe method in is synchronous, and theHashMapThe methods in are non-synchronous by default. In a multi-threaded concurrency environment, you can directly useHashtable, but to useHashMap, you need to increase the synchronization process. ThirdHashtableInKeyAndvalueAre not allowed to appearNULLValue. InHashMapInNULLCan be used as a key, such a key only one, can have one or more keys corresponding to the value ofNULL。 WhenGet() method returnsNULLValue, that is, you can representHashMapDoes not have the key, or it can indicate that the key corresponds to a value ofNULL。 Therefore, inHashMapcannot be determined by theGet() method to determineHashMapIf there is a key in theContainsKey() method to judge. The internal implementation of the two traversal methods is different.Hashtable、HashMaphas been usedIterator。 And because of historical reasons,Hashtablealso uses theEnumerationThe way. The use of the hash value is different,HashTableDirectly using the object'shashcode。 andHashMapRecalculateHashValue. SixthHashtableAndHashMapThey are the initial size of an array of two internal implementations and how to scale up.HashTableInHashThe default size of the array is 11, and the way to increase it is Old*2+1.HashMapInHashThe default size of the array is 16, and must be an exponent of 2.

3, Weakhashmap class
Weakhashmap is an improved hashmap, which implements a "weak reference" to key, which can be recycled by GC if a key is no longer referenced externally.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Several Java containers you must Know (collection Class)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.