ArrayList / Vector / LinkedList difference and usage

ArrayList and Vector is the use of an array of stored data, this number of array elements is greater than data actually stored in order to increase and insertion elements, allows direct serial index element, but the insert data to design the array elements move like a memory operation, the index data quickly inserted slow data, Vector method since a synchronized (thread-safe) so the worse performance than ArrayList, the LinkedList implemented using a doubly linked list is stored, indexed by serial number data requires traversing forward or backward, but only needs to insert the data item records the present the keys to the front and rear, so insert several fast! Linear table, linked lists, hash table is a common data structure, making Java development time, JDK has provided us with a series of corresponding classes to implement basic data structures. These classes are in the java.util package. This paper attempts to simple description to explain the role of each class of the reader and how to use these classes correct.
Collection

List
│├LinkedList
│├ArrayList
│└Vector
│ └Stack
└Set
Map
├Hashtable
├HashMap
└WeakHashMap

 Collection Interface

Collection is the most basic set of interfaces, a Collection represents a group of Object, i.e. Collection element (Elements). Collection allows the same number of elements and not others. Some sort while others can not. Java SDK does not provide directly inherited from the Collection classes, Java SDK provides classes that are inherited from the Collection of the sub-interfaces such as List and Set. All classes implement Collection interface must provide two standard constructors: no argument constructor used to create an empty Collection, Collection has a constructor parameter for creating a new Collection, this new Collection and Mass the Collection has the same elements. After a constructor allows a user to copy a Collection. How to traverse each element in the Collection? Regardless of how the actual type Collection, which support an iterator () method, which returns an iterator, iterator can use the visits to each element of each Collection. A typical usage is as follows:
Iterator it = collection.iterator(); // 获得一个迭代子
while(it.hasNext()) {
  Object obj = it.next(); // 得到下一个元素
}
Derived from the Collection interface of two interfaces is List and Set.

List Interface

List is ordered Collection, use this interface to accurately control the position of insertion of each element. Users can use index (List elements in the position, similar to the array subscript) to access elements in the List, which is similar to an array of Java. Set to be mentioned and following different, List allows the same elements . Collection iterator addition to the necessary interface () method, List also provides a listIterator () method returns a ListIterator interface and standard Iterator interface compared, a few more ListIterator add () method or the like, allows to add, delete, set elements, but also traversing forward or backward. List interfaces to achieve common class of LinkedList, ArrayList, Vector, and Stack.

LinkedList class

LinkedList implements List interface that allows null elements. In addition to provide additional LinkedList get, remove, insert method in LinkedList the first or tail. LinkedList these operations may be used as a stack (stack), a queue (Queue) or double-ended queue (deque). Note that no synchronization LinkedList method. If multiple threads access a List, they must implement their own access synchronization. One solution is a synchronization when creating List of List structure:
List list = Collections.synchronizedList(new LinkedList(...));

 ArrayList class

ArrayList implements an array of variable size. It allows all the elements, including null. ArrayList is not synchronized. size, isEmpty, get, set method of running time is constant. But add methods for the assessment of a constant, add n elements need to O (n) time. Other methods running time is linear. Each ArrayList instance has a capacity (Capacity), i.e., for the size of the array elements stored. With the capacity to add new elements to increase automatically, but growth algorithm is not defined. When the need to insert a large number of elements, the insert can be called ensureCapacity ArrayList method to increase the capacity to improve the efficiency of insertion. And LinkedList, ArrayList is non-synchronous of (unsynchronized).

Vector class

Vector is very similar to the ArrayList, but Vector is synchronized in. Created by Vector Iterator, although ArrayList created Iterator is the same interface, but because Vector is synchronized, when a Iterator been created and is being used by another thread Vector change the status of (for example, add or delete some element), then call when the method Iterator will throw ConcurrentModificationException, it is necessary to catch the exception.

Stack class

Stack inherited from Vector, to implement a LIFO stack. Stack provide five additional approach allows Vector to be used as a stack. The push and pop the basic method, there is obtained a method Zhanding elements peek, empty method to test whether the stack is empty, search method of detecting the position of an element in the stack. Stack after stack is empty just created.

Set Interface

Is a Set does not contain duplicate elements Collection, i.e., any two elements e1 and e2 are e1.equals (e2) = false, Set up to a null element. Clearly, there is a Set constructor constraint, the incoming Collection parameter can not contain duplicate elements. Please note: You must be careful operation variable object (Mutable Object). If a variable element Set in the state to change its own cause Object.equals (Object) = true will cause some problems.

Map Interface

Please note, Map Collection interfaces do not inherit, Map provides the mapping key to value. Map can not contain the same key, each key can map a value. Map interface provides three kinds of pools view, Map content can be set as a key group, a group set value, or a set of key-value mappings.

Hashtable class

Hashtable inherited Map interface, the hash table a key-value mapping. Any object of non-empty (non-null) can be used as a key or value. Add data using put (key, value), using the extracted data get (key), the two basic operation time overhead is constant. Hashtable adjusted through initial capacity and load factor two parameters. Usually the default load factor 0.75 better achieved the balance of time and space. Increasing the load factor can save space but find the corresponding time will increase, which will affect operations such as get and put. Hashtable using the following simple example, the 1,2,3 into the Hashtable, their key are "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));
To remove a number, such as 2, with the corresponding key:
 Integer n = (Integer)numbers.get(“two”);
    System.out.println(“two = ” + n);
Since the object as a key to determine the location of the corresponding value calculated by the hash function, so any object as a key must implement equals and hashCode method. hashCode and equals method inherited from the root class Object, if you use self-defined as a class key, then, to be very careful, as defined by the hash function, if two objects are the same, namely obj1.equals (obj2) = true, then their hashCode must be the same, but if the two objects are different, they are not necessarily the hashCode different if two different hashCode the same object, a phenomenon known as conflict, conflict will lead to operating time overhead hash table increases, Therefore, as defined hashCode () method, can speed up the operation of the hash table. If the same object has different hashCode, operation of the hash table unexpected results occur (expected get method returns null), to avoid this problem, one need only remember: equals the same time replication methods and hashCode methods, and do not just write one of them. Hashtable is synchronized.

HashMap class

Hashtable HashMap and the like, except that the HashMap non-synchronized, and allow null, null value and null key. , But when considered HashMap Collection (values ​​() method returns the Collection), which is proportional to the capacity of the iterator operation time expenses and HashMap. Therefore, if the performance of iterative important operation, it will not HashMap initialization for the high capacity, or load factor too low.

WeakHashMap class

WeakHashMap the HashMap is an improved, its key implementation of "weak references", if a key is no longer referenced by an external, then the key can be recovered GC.

to sum up

If it comes to operating stacks, queues, etc., should consider the use of List, the need to quickly insert, delete elements, you should use LinkedList, if you need fast random access to elements, you should use ArrayList. If the program, or access only in a thread in a single-threaded environment, consider the asynchronous class, the higher the efficiency, if multiple threads may also operate a class, the class should be used to synchronize. Pay special attention to the operation of the hash table, as a key target to correct replication equals and hashCode methods. Try to return to the interface instead of the actual type, such as return List rather than ArrayList, so that if you later need to be replaced ArrayList LinkedList, client code need not change. This is for the abstract programming. Synchronization Vector is synchronized. Some methods in this class to ensure that the Vector objects are thread-safe. The ArrayList is asynchronous, so the object is not thread-safe in the ArrayList. Because synchronization requirements will affect the efficiency of the implementation, so if you do not thread-safe, then use ArrayList is a good choice, because of the synchronization to avoid unnecessary performance overhead. Data from internal growth in terms of implementation mechanism ArrayList and Vector are using an array (Array) to control objects in the collection. When you add an element to these two types of time, if the number of elements beyond the current length of the internal array they need to extend the length of the interior of the array, the array automatically increase the length of the original double default under Vector, ArrayList is the original 50% So this set the space occupied by the end you get always bigger than you actually need. So if you want to save a large amount of data in the pool then use the Vector has some advantages, because you can set the initial size of the set of resources to avoid unnecessary overhead. Find data (through index) or an increase in the end of the collection, removal time it takes an element is the same usage patterns in the ArrayList and Vector, from a specified location, this time we use the O (1). However, if the addition or removal of elements set at other locations so the time it takes the linear growth: O (ni), where n represents the number of elements in the set, i of the index representative of the position of addition or removal of elements of the element. Why is this so? When carrying out the above operation is that all the elements in the first set after the i-th element and i have to perform shift operation. What does this all mean? This means that you only find elements of a specific location or only at the end of the set increases, remove elements, then use the Vector or ArrayList can be. If other operations, you'd better choose another set of operations. For example, LinkList collections increase or remove any elements of the collection takes the position is the same? O (1), but it uses a missing element of the index is relatively slow -O (i), where i is index position. ArrayList also very easy to use, because you can simply use the index to replace the iterator object creation operation. LinkList will create objects for each element inserted, all you have to understand that it will bring additional costs. Finally, in "Practical Java" book Peter Haggar is recommended to use a simple array (Array) to replace Vector or ArrayList. Especially for high efficiency requirements of the program even more so. Because the use of an array (Array) synchronous avoid additional and unnecessary method called re-allocation of space operations. Reference: [1]. http://www.cnblogs.com/mgod/archive/2007/08/05/844011.html

Reproduced in: https: //my.oschina.net/itfanr/blog/195625

Guess you like

Origin blog.csdn.net/weixin_33843947/article/details/91799377