Differences and usages of Java ArrayList, vectors, and LinkedList

Source: Internet
Author: User
Tags array length

Differences and usages of Java ArrayList, vectors, and linkedlist (RPM)

ArrayList and Vector is to take the array format to store data, this array element is larger than the actual data stored in order to grow and insert elements, both allow the direct ordinal index element, but the insertion of data to design to the array element movement and other memory manipulation, so the index data fast insertion data slow, Vector because of the application of the Synchronized method (line Cheng Anhan) So the function is worse than ArrayList, LinkedList application of two-way linked list to achieve storage, index data by ordinal need to traverse forward or backward, but insert data only need to record the item before and after items can be, So insert several faster!

Linear table, linked list, hash table is a commonly used data layout, in the Java opening up, the JDK has provided us with a series of response classes to achieve the root base of the data layout. These classes are all in the Java.util package. This paper attempts to explain the influence of each class and how to apply these classes correctly through the simple description of the process.

Collection
├list
│├linkedlist
│├arraylist
│└vector
│└stack
└set
Map
├hashtable
├hashmap
└weakhashmap

Collection interface
Collection is the aggregates interface for the root of the base, and a collection represents a set of object, the element of collection (Elements). Some collection allow identical elements while others are not. Some can sort and others cannot. The Java SDK does not supply classes that directly persist from collection, and the Java SDK provides classes that are "sub-interfaces" such as list and set that are persisted from collection.
All classes that implement the collection interface must supply two standard organ functions: The parameterless organ function is used to create an empty collection, and an organ function with a collection parameter is used to create a new collection, This new collection has the same elements as the incoming collection. The latter function allows the user to copy a collection.
How do I traverse every element in the collection? What is the actual type of collection, which supports a iterator () method that returns an iteration, and applies the iteration to one by one to receive each element in the collection. Examples of usage are as follows:
Iterator it = Collection.iterator (); Get an iteration child
while (It.hasnext ()) {
Object obj = It.next (); Get the next element
}
The two interfaces that are derived from the collection interface are list and set.

List interface
The list is an ordered collection, and the application of this interface may correctly grasp the position of each element inserted. The user may apply an index (the element's position in the list, similar to an array subscript) to receive an element in the list, similar to an array of java.
The list allows for the same elements as the set mentioned below.
In addition to the iterator () method with the collection interface, the list also provides a listiterator () method that returns a Listiterator interface, compared to the standard iterator interface, Listiterator has a number of add () methods, allowing the addition, deletion, setting elements, and the ability to traverse forward or backward.
The common classes that implement the list interface are Linkedlist,arraylist,vector and stacks.

LinkedList class
LinkedList implements the list interface, allowing null elements. Additionally the LinkedList is supplied with extra get,remove, in the first or tail of the LinkedList. These manipulations enable the LinkedList to be used as a pub (stack), queue, or bidirectional queue (deque).
Pay attention to LinkedList no synchronization method. If multiple threads are receiving a list at the same time, they must implement an interview synchronization itself. One workaround is to create a list in which to close a synchronized list:
List List = Collections.synchronizedlist (New LinkedList (... ));

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 allocation constant, when adding n elements requires O (n). The other way to run time is linear.
Each ArrayList instance has a capacity (capacity), which is the size of the array used to store the elements. This capacity is actively growing with the addition of new elements, but the growth algorithm is not defined. When multiple elements need to be inserted, the Ensurecapacity method can be called before inserting to increase the capacity of ArrayList to improve insertion effectiveness.
Like LinkedList, ArrayList are also synchronized (unsynchronized).

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

Stack class
The stack continues from vector, realizing a straggling first-out inn. Stack provides 5 additional ways to make the vector count as a pub application. Foundine basic push and pop methods, as well as peek method to get the stack top elements, empty method Test inn is empty, search method to detect an element in the status of the inn. Stack has just been created as an empty stack.

Set interface
Set is a collection that does not contain repeated elements, that is, the random two elements E1 and E2 have E1.equals (E2) =false,set have a maximum of one null element.
Obviously, the set of the organ function has a binding premise, the incoming collection parameter cannot contain repeated elements.
Please pay attention to: you must be wary of manipulating mutable objects (Mutable object). If a mutable element in a set changes its condition, object.equals (Object) =true will cause some problems.

Map interface
Please note that map does not have a continuous collection interface, and map supplies a mapping of key to value. A map cannot contain identical keys, and each key can only map one value. The map interface provides 3 aggregates views, and the contents of the map can be counted as a set of key aggregates, a set of value aggregates, or a set of key-value mappings.

Hashtable class
The Hashtable continues 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 apply put (key, value), take out the data apply get (key), these two root base manipulate the time overhead is constant.
Hashtable through the process initial capacity and load factor two parameters of the dispensing function. The default load factor 0.75 is a good way to achieve time and space balance. Increasing the load factor can save space but the response will increase in the lookup time, which will affect the manipulation like get and put.
A simple example of applying Hashtable would be to put the three-to-one in Hashtable, with their key being "single", "Two", "three", respectively:
Hashtable numbers = new Hashtable ();
Numbers.put ("One", New Integer (1));
Numbers.put ("n", New Integer (2));
Numbers.put ("Three", New Integer (3));
To remove a number, such as 2, with the response key:
Integer n = (integer) numbers.get ("a");
System.out.println ("both =" + N);
Because the object that is a key is going through the process of plotting its hash function to determine the position of the corresponding value, it is necessary to implement the hashcode and Equals methods with any object that is a key. The hashcode and Equals methods persist from the root class object, and if you use a custom class to count as key, be quite wary of following the definition of the hash function, if two objects are identical, namely Obj1.equals (OBJ2) =true, Their hashcode must be identical, but if two objects are not the same, then their hashcode is not necessarily incompatible, if the two non-object hashcode identical, this phenomenon is called conflict, the conflict will lead to manipulate the hash table when the overhead increases, So as far as possible to define a good hashcode () method, can speed up the manipulation of the hash table.
If the same object has hashcode, the manipulation of the hash table will have unexpected results (waiting for the Get method to return null), to avoid this problem, only need to remember one: the simultaneous replication of the Equals method and Hashcode method, and not only write this one.
The Hashtable is synchronous.

HashMap class
HashMap is similar to Hashtable, where the HashMap is synchronous and allows null, that is, null value and null key. , but when HashMap is considered collection (the values () method can return collection), its iteration is manipulated by the time the cost is proportional to the capacity of the HashMap. is to, if the function of iterative manipulation is very important, do not set HASHMAP initialization capacity too high, or load factor too low.

Weakhashmap class
Weakhashmap is an improved hashmap, which is a "weak reference" to the key experiment, and if a key is no longer referenced externally, then the key can be taken over by GC.

Summarize
If it is related to the inn, queue and other manipulation, should be refined with the list, for the need to quickly insert, delete elements, should apply LinkedList, if the need to quickly random interview elements, should be applied ArrayList.
If the application is in a single-threaded view, or if an interview is performed on only one thread, the non-synchronous class is more efficient, and if multiple threads might manipulate a class at the same time, the synchronized class should be applied.
To keep a focus on manipulating the hash table, the object being key is to correctly replicate the Equals and Hashcode methods.
Try to return the interface instead of the actual type, such as returning list instead of ArrayList, such as Chujo is the future need to change ArrayList to LinkedList, the client code does not change. This is for abstract programming.

Synchronization of
The vectors are synchronized. Some of the methods in this class ensure that the objects in the vector are line Cheng Anhan. The ArrayList is asynchronous, and the object in ArrayList is not a line Cheng Anhan. Because synchronous requests can affect the effectiveness of fulfillment, it is a good choice to apply ArrayList if you do not need the aggregates of the line Cheng Anhan, which avoids the unnecessary overhead of synchronization.
Data growth
From the internal implementation mechanism, ArrayList and vectors are applied arrays (array) to grasp the objects in the set. When you increase the elements in these two types of time, if the number of elements outside the internal array of the length of the present, they need to expand the length of the internal array, vector default image of the active growth of the array length, ArrayList is the original 50%, So at the end of the aggregates, the space you get is always bigger than what you actually need. So if you're going to be concentrating on storing multiple amounts of data, then applying a vector has some advantage, because you can set the initialization size of the aggregates in the process to avoid unnecessary data overhead.
Application Mode
In ArrayList and vectors, it is the same when looking for data from a given status (through the process index) or growing at the end of a aggregates, removing an element, and at this point we use O (1) as a tacit indication. But, if the other status of aggregates growth or removal of the element will be a linear growth: O (n-i), which n represents the number of elements in the cluster, I represents the element growth or removal of the index position of the element. Why is it so? It is believed that all elements after the first and second elements of the above-mentioned manipulation shall perform the operation of displacement. What does all this mean?
This means that you are just looking for a particular status element or only to grow and remove elements at the end of the aggregates, then apply either a vector or a ArrayList. If it is another operation, you'd better choose other aggregates to manipulate the class. For example, does the linklist aggregates class spend the same time growing or removing elements of any position in the cluster? O (1), but it's applied in the index of an element the lack of difficulty is slow-O (i), where I is the status of the index. It is also easy to apply ArrayList because you can simply apply an index to replace the manipulation of creating iterator objects. Linklist also creates objects for each inserted element, all of which you need to be familiar with to ask for additional overhead.
Finally, in the book Practical Java, Peter Haggar recommends applying a simple array to replace vectors or ArrayList. This is especially true for those with high requests for performance. Because an array is applied, it avoids synchronization, additional method calls, and unnecessary manipulation of the scratch space.

Article excerpt from:

Http://edu.21cn.com/linux/g_188_650560-1.htm

http://blog.csdn.net/sunboy_2050/article/details/7667364

Differences and usages of Java ArrayList, vectors, and linkedlist (RPM)

Related Article

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.