The difference of set,list,map,vector,arraylist--data structure and algorithm

Source: Internet
Author: User
Tags concurrentmodificationexception
Turn from: http://www.cnblogs.com/hnrainll/archive/2013/04/08/3006638.html


The difference between the Set,list,map,vector,arraylist

The difference between the Set,list,map,vector,arraylist

Java Container---List,map,set
Collection
├list
│├linkedlist
│├arraylist
│└vector
│└stack
└set
Map
├hashtable
├hashmap
└weakhashmap

The

Collection Interface  
Collection is the most basic collection 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 be sorted and others not. The Java SDK does not provide classes that directly inherit from collection, and the Java SDK provides classes that inherit from collection such as list and set. &NBSP
All classes that implement the collection interface must provide two standard constructors: parameterless constructors are used to create an empty collection, and a constructor for a collection parameter is used to create a new collection. This new collection has the same element as the incoming collection. The latter constructor allows the user to replicate a collection. &NBSP
How to traverse every element in the collection. Regardless of the actual type of collection, it supports a iterator () method that returns an iteration that can be used to access each element of the collection one at a time.       Typical usage is as follows:  
Iterator it = Collection.iterator ();//Get an iteration  
while (It.hasnext ()) { 
Object obj = It.next (); Gets 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, using this interface to precisely control where each element is inserted. The user can access the elements in the list, similar to the Java array, by using the index (the position of the element in the list, similar to the array subscript).
Unlike the set mentioned below, the list allows the same elements.
In addition to the iterator () method with the collection interface prerequisites, the list also provides a listiterator () method that returns a Listiterator interface, compared to the standard iterator interface, There are a number of add () listiterator that allow adding, deleting, setting elements, and traversing forward or backwards.
Common classes that implement the list interface are Linkedlist,arraylist,vector and stack.

LinkedList class
LinkedList implements the list interface, allowing null elements. Additionally LinkedList provides additional Get,remove,insert methods at LinkedList's header or tail. These operations enable LinkedList to be used as stacks (stack), queues (queue), or bidirectional queues (deque).
Note that 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 when the list is created:
List List = Collections.synchronizedlist (new LinkedList (...));

ArrayList class
ArrayList implements a variable sized array. It allows all elements, including null. ArrayList is not synchronized.
The Size,isempty,get,set method runs at a constant time. However, the Add method cost is the allocated constant, and the time of O (n) is required to add n elements. The 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 can automatically increase 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 increase the insertion efficiency.
Like LinkedList, ArrayList is also unsynchronized (unsynchronized).

Vector class
Vectors are very similar to ArrayList, but vectors are synchronized. Iterator created by vector, although the same interface was created with ArrayList, but because vectors are synchronized, and when one iterator is created and is being used, another thread changes the state of the vector (for example, Add or remove some elements), the concurrentmodificationexception is thrown when the iterator method is invoked, so the exception must be caught.

Stack class
Stack inherits from the vector, implementing a LIFO stack. Stack provides 5 additional methods that allow vectors to be used as stacks. Basic push and Pop methods, and Peek method to get the top of the stack elements, empty method test stack is empty, the search method detects an element in the stack position. Stack is just created after stack is empty.

Set interface
A 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.
Obviously, the constructor of the set has a constraint, and the incoming collection parameter cannot contain duplicate elements.
Note: You must be careful to manipulate variable objects (mutable object). If a variable element in a set changes its state, causing the Object.Equals (Object) =true to cause some problems.

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

Hashtable class
Hashtable inherits the map interface and implements a hash table of key-value mappings. Any object that is Non-null (non-null) can be a key or value.
Adding data using put (key, value), fetching data using get (key), the time cost of these two basic operations is constant.
Hashtable adjusts performance by initial capacity and load factor two parameters. Typically, the default load factor 0.75 achieves a better balance of time and space. Increasing the load factor saves space but the corresponding lookup time increases, which can affect operations like get and put.
Using Hashtable for example, put 1,2,3 into Hashtable, their key is "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, use the corresponding key:
Integer n = (integer) numbers.get ("two");
System.out.println ("two =" + N);
Because an object that is a key will determine the location 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 a key, be very careful, as defined by the hash function, if two objects are the same, that is, Obj1.equals (OBJ2) =true, Their hashcode must be the same, but if two objects are different, their hashcode is not necessarily different, and if the hashcode of two different objects is the same, this phenomenon is called conflict, and the conflict causes the time overhead of manipulating the hash table, so as to define the hashcode () method to speed up the operation of the hash table.
If the same object has a different hashcode, the operation of the hash table will have unexpected results (the expected GET method returns null), to avoid this problem, you need to keep in mind one: you have to copy both the Equals method and the Hashcode method, not just one.
The Hashtable is synchronized.

HashMap class
HashMap is similar to Hashtable, except that HashMap is unsynchronized and allows NULL, that is, null value and null key. , but when HashMap is treated as collection (the values () method returns collection), its iterative child operation time cost is proportional to the capacity of the HashMap. Therefore, if the performance of an iterative operation is significant, do not set the HASHMAP initialization capacity too high, or the load factor too low.

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

Summarize
If you are involved in stacks, queues, and other operations, you should consider using the list, for the need to quickly insert, delete elements, should use LinkedList, if you need to quickly randomly access elements, you should use ArrayList.
If the program is in a single-threaded environment, or if access is only done in one thread, it is more efficient to consider a class that is not synchronized, and should use a synchronized class if multiple threads might be working on a class at the same time.
Special attention should be paid to the operation of the hash table, where the object of the key is correctly hashcode the Equals and the method.
Try to return the interface instead of the actual type, such as returning a list instead of ArrayList, so that if you need to replace ArrayList with LinkedList later, the client code does not have to change. This is for abstract programming.

Java Collection Class map set list ArrayList HashMap Hashtable

Vector methods are synchronous (Synchronized), Thread-safe (Thread-safe), and ArrayList's approach is not that because the synchronization of threads necessarily affects performance, ArrayList performance is better than vector.
When the element in the vector or ArrayList exceeds its initial size, the vector doubles its capacity, while the ArrayList only increases by 50%, so that ArrayList is useful for saving memory space.
Hashtable and HashMap
Their performance comparisons are similar to vectors and ArrayList, such as the Hashtable approach is synchronized, and the HashMap is not.
ArrayList and LinkedList
For processing a list of data items, Java provides two classes ArrayList and linkedlist,arraylist internal implementations are based on an internal array object[], so conceptually, it's more like an array, But LinkedList's internal implementation is based on a set of connected records, so it's more like a list structure, so there's a big difference in performance.
(1) From the above analysis, in the front or the middle of the ArrayList insert data, you have to move all subsequent data backwards, which will take a lot of time, so when you add data to a column of data instead of in front or in the middle, and you need to randomly access the elements, Using ArrayList provides better performance.
(2) while accessing an element in a linked list, you have to look at one end of the list to find the element along the direction of the connection, until you find the elements you want, so when you are adding or deleting data in front or in the middle of a column of data, and accessing the elements in the order, You should use the LinkedList.
(3) If in the programming, 1, 22 kinds of situations alternately appear, at this time, you may consider using the list such general interface, but does not care about the concrete implementation, in the concrete situation, its performance is guaranteed by the concrete realization.
Set the initial size of the collection class
The size of most classes in the Java Collection framework can be increased correspondingly as the number of elements increases. We don't seem to care about its initial size, but if we consider the performance of a class, it's important to consider setting the initial size of the collection object as much as possible, which will greatly improve the performance of the code, for example, Hashtable the default initial size is 101 and the load factor is 0.75, which means that if there are more than 75 elements, it must increase the size and rearrange the elements, so if you know that the exact number of elements is 110 when you create a new Hashtable object, You should set its initial size to 110/0.75=148 so that you can avoid the need to rearrange the memory and increase the size.
Especially to understand:
Hashtable class
Hashtable inherits the map interface and implements a hash table of key-value mappings. Any object that is Non-null (non-null) can be a key or value.
Adding data using put (key, value), fetching data using get (key), the time cost of these two basic operations is constant.
Hashtable adjusts performance by initial capacity and load factor two parameters. Typically, the default load factor 0.75 achieves a better balance of time and space. Increasing the load factor saves space but the corresponding lookup time increases, which can affect operations like get and put.
Using Hashtable for example, put 1,2,3 into Hashtable, their key is "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, use the corresponding key:
Integer n = (integer) numbers.get ("two");
System.out.println ("two =" + N);
Because an object that is a key will determine the location 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 a key, be very careful, as defined by the hash function, if two objects are the same, that is, Obj1.equals (OBJ2) =true, Their hashcode must be the same, but if two objects are different, their hashcode is not necessarily different, and if the hashcode of two different objects is the same, this phenomenon is called conflict, and the conflict causes the time overhead of manipulating the hash table, so as to define the hashcode () method to speed up the operation of the hash table.
If the same object has a different hashcode, the operation of the hash table will have unexpected results (the expected GET method returns null), to avoid this problem, you need to keep in mind one: you have to copy both the Equals method and the Hashcode method, not just one.
The Hashtable is synchronized.
HashMap class
HashMap is similar to Hashtable, except that HashMap is unsynchronized and allows NULL, that is, null value and null key. , but when HashMap is treated as collection (the values () method returns collection), its iterative child operation time cost is proportional to the capacity of the HashMap. Therefore, if the performance of an iterative operation is significant, do not set the HASHMAP initialization capacity too high, or the load factor too low.
LinkedList class
LinkedList implements the list interface, allowing null elements. Additionally LinkedList provides additional Get,remove,insert methods at LinkedList's header or tail. These operations enable LinkedList to be used as stacks (stack), queues (queue), or bidirectional queues (deque).
Note that 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 when the list is created:
List List = Collections.synchronizedlist (new LinkedList (...));
ArrayList class
ArrayList implements a variable sized array. It allows all elements, including null. ArrayList is not synchronized.
The Size,isempty,get,set method runs at a constant time. However, the Add method cost is the allocated constant, and the time of O (n) is required to add n elements. The 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 can automatically increase 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 increase the insertion efficiency.
Like LinkedList, ArrayList is also unsynchronized (unsynchronized).
Vector class
Vectors are very similar to ArrayList, but vectors are synchronized. Iterator created by vector, although the same interface was created with ArrayList, but because vectors are synchronized, and when one iterator is created and is being used, another thread changes the state of the vector (for example, Add or remove some elements), the concurrentmodificationexception is thrown when the iterator method is invoked, so the exception must be caught.

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.