Differences between Java container class List, ArrayList, Vector, map, HashTable, and HashMap

Source: Internet
Author: User

ArrayList and HashMap are asynchronous, while Vector and HashTable are synchronous. Therefore, Vector and HashTable are thread-safe, while ArrayList and HashMap are not thread-safe. Because synchronization takes machine time, the execution efficiency of Vector and HashTable is lower than that of ArrayList and HashMap. Collection sorted List interface │ ordered List linked List │ ordered ArrayList ordered structure dynamic array class │ ordered Vector │ ordered Stack sorted Set Map worker Hashtable worker HashMap worker WeakHashMap List interface List is an ordered Collection, you can use this interface to precisely control the insert position of each element. You can use an index (the position of an element in the List, similar to an array subscript) to access the elements in the List, which is similar to an array in Java. Unlike the Set mentioned below, the List can have the same element. In addition to the iterator () method required for the Collection interface, List also provides a listIterator () method to return a ListIterator interface. Compared with the standard Iterator interface, ListIterator has some more add () you can add, delete, and set elements to traverse forward or backward. Common classes that implement the List interface include the List, ArrayList, Vector, and Stack. ArrayList class ArrayList implements an array of variable sizes. It allows all elements, including null. ArrayList is not synchronized. Size, isEmpty, get, set method running time is constant. However, the overhead of the add method is the constant of the allocation. It takes O (n) to add n elements. The running time of other methods is linear. Each ArrayList instance has a Capacity, that is, the size of the array used to store elements. This capacity can automatically increase with the addition of new elements, but the growth algorithm is not defined. When a large number of elements need to be inserted, you can call the ensureCapacity method before insertion to increase the ArrayList capacity to improve the insertion efficiency. Like the synchronized list, ArrayList is also non-synchronous (unsynchronized ). Note that Map does not inherit the Collection interface. Map provides the key ing from key to value. A Map cannot contain the same key, and each key can only Map one value. The Map interface provides three sets of views. The Map content can be treated as a set of keys, a set of values, or a set of key-value ing. The HashMap class HashMap is similar to Hashtable. The difference is that HashMap is non-synchronous and allows null, that is, null value and null key ., However, when HashMap is treated as a Collection (the values () method can return the Collection), its iteration suboperation time overhead is proportional to the capacity of HashMap. Therefore, if the performance of iterative operations is very important, do not set the HashMap initialization capacity too high or the load factor too low. Collection Interface Collection is the most basic Collection interface. A Collection interface represents a group of objects, that is, Elements of the Collection ). Some collections allow the same elements while others do not. Some can be sorted, while others cannot. The Java SDK does not provide classes that directly inherit from collections. The classes provided by the Java SDK are the "subinterfaces" that inherit from collections, such as List and Set. All classes that implement the Collection interface must provide two standard constructor: A non-parameter constructor is used to create an empty Collection, A constructor with the Collection parameter is used to create a new Collection, which has the same elements as the imported Collection. The next constructor allows you to copy a Collection. How to traverse every element in the Collection? Regardless of the actual type of Collection, it supports an iterator () method. This method returns an iterator, and each element in the Collection can be accessed one by one using this iterator. Typical usage: Iterator it = collection. iterator (); // get an iterator while (it. hasNext () {Object obj = it. next (); // get the next element}. The two interfaces derived from the Collection interface are List and Set. The List interface List is an ordered Collection, which can be used to precisely control the insert position of each element. You can use an index (the position of an element in the List, similar to an array subscript) to access the elements in the List, which is similar to an array in Java. Unlike the Set mentioned below, the List can have the same element. In addition to the iterator () method required for the Collection interface, List also provides a listIterator () method to return a ListIterator interface. Compared with the standard Iterator interface, ListIterator has some more add () you can add, delete, and set elements to traverse forward or backward. Implements the List interface, which is a S inkedList, ArrayList, Vector, and Stack. The listlist class implements the List interface, allowing null elements. In addition, the values list provides additional get, remove, and insert methods at the beginning or end of the values list. These operations enable the queue list to be used as a stack, queue, or two-way queue (deque ). Note that the synchronized list method is not available. If multiple threads access a List at the same time, they must implement access synchronization by themselves. One solution is to construct a synchronized List when creating a List: List list = Collections. synchronizedList (new synchronized list (...)); arrayList class ArrayList implements an array of variable sizes. It allows all elements, including null. ArrayList is not synchronized. Size, isEmpty, get, set method running time is constant. However, the overhead of the add method is the constant of the allocation. It takes O (n) to add n elements. The running time of other methods is linear. Each ArrayList instance has a Capacity, that is, the size of the array used to store elements. This capacity can automatically increase with the addition of new elements, but the growth algorithm is not defined. When a large number of elements need to be inserted, you can call the ensureCapacity method before insertion to increase the ArrayList capacity to improve the insertion efficiency. Like the synchronized list, ArrayList is also non-synchronous (unsynchronized ). The Vector class Vector is very similar to ArrayList, but the Vector is synchronized. Although the Iterator created by Vector is the same interface as the Iterator created by ArrayList, because Vector is synchronous, when an Iterator is created and in use, another thread changes the state of the Vector (for example, adding or deleting some elements). When calling the Iterator method, ConcurrentModificationException is thrown. Therefore, this exception must be caught. Stack stacks inherit from the Vector to implement a post-import, first-out Stack. Stack provides five additional methods to make the Vector used as a Stack. The basic push and pop methods also include the elements of the peek method to get the top of the stack. The empty method tests whether the stack is empty. The search method checks the position of an element in the stack. The Stack is empty after being created. The Set interface Set is a Collection that does not contain repeated elements, that is, the two elements e1 and e2 both have e1.equals (e2) = false, and the Set interface has a maximum of null elements. Obviously, the Set constructor has a constraint that the imported Collection parameter cannot contain repeated elements. Note: You must be careful when operating Mutable objects ). If a variable element in a Set changes its state, Object. equals (Object) = true may cause some problems. Note that Map does not inherit the Collection interface. Map provides the key ing from key to value. A Map cannot contain the same key, and each key can only Map one value. The Map interface provides three sets of views. The Map content can be treated as a set of keys, a set of values, or a set of key-value ing. The Hashtable class inherits the Map interface and implements a key-value ing hash table. Any non-null object can be used as a key or value. Put (key, value) is used for adding data, and get (key) is used for retrieving data. The time overhead of these two basic operations is constant. Hashtable uses the initial capacity and load factor parameters to adjust the performance. Generally, the default load factor 0.75 achieves a better balance between time and space. Increasing the load factor can save space, but the corresponding search time will increase, which affects operations such as get and put. A simple example of Hashtable is as follows: Put 1, 2, 3 into Hashtable, and their keys 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 retrieve a number, such as 2, use the corresponding key: Integer n = (Integer) numbers. get ("two"); System. out. println ("two =" + n); because the object as the key is determined by calculating its hash function, therefore, any object as a key must implement the hashCode and equals methods. The hashCode and equals Methods inherit from the root class Object. If you use a custom class as the key, be very careful. According to the definition of the hash function, if the two objects are the same, that is, if obj1.equals (obj2) = true, their hashCode must be the same, but if two objects are different, their hashCode is not necessarily different. If the hashCode of two different objects is the same, this phenomenon is called a conflict. A conflict will increase the time overhead for operating the hash table. Therefore, the hashCode () method should be defined as much as possible to speed up the operation of the hash table. If the same object has different hashCode, operations on the hash table will produce unexpected results (the expected get method returns null). To avoid this problem, you only need to remember one: the equals and hashCode methods must be rewritten at the same time, instead of writing only one of them. Hashtable is synchronous. The HashMap class HashMap is similar to Hashtable. The difference is that HashMap is non-synchronous and allows null, that is, null value and null key ., However, when HashMap is treated as a Collection (the values () method can return the Collection), its iteration suboperation time overhead is proportional to the capacity of HashMap. Therefore, if the performance of iterative operations is very important, do not set the HashMap initialization capacity too high or the load factor too low. WeakHashMap class WeakHashMap is an improved HashMap that implements "weak references" to keys. If a key is no longer referenced by external entities, it can be recycled by GC. To sum up, if operations such as stacks and queues are involved, you should consider using the List. For elements that need to be inserted and deleted quickly, you should use the sort List. If you need to quickly access elements randomly, you should use the ArrayList. If the program is in a single-threaded environment or the access is only performed in one thread, the efficiency of non-synchronous classes is high. If multiple threads may operate on one class at the same time, synchronous classes should be used. Pay special attention to the operations on the hash table. The equals and hashCode methods should be correctly rewritten as the key object. Try to return the interface rather than the actual type. For example, if the List is returned rather than the ArrayList, the client code does not need to be changed if you need to replace the ArrayList with the explain List later. This is for abstract programming. Synchronous Vector is synchronous. Some methods in this class ensure that the objects in the Vector are thread-safe. ArrayList is asynchronous, so the objects in ArrayList are not thread-safe. Because the synchronization requirements will affect the execution efficiency, it is a good choice to use ArrayList if you do not need a thread-safe set, this avoids unnecessary performance overhead due to synchronization. In terms of the internal implementation mechanism of data growth, both ArrayList and Vector use arrays to control objects in a set. When you add elements to these two types, if the number of elements exceeds the current length of the internal array, both of them need to extend the length of the internal array, by default, Vector automatically doubles the length of the original array, and ArrayList is 50% of the original length. Therefore, the space occupied by this set is always larger than what you actually need. Therefore, if you want to save a large amount of data in the collection, using Vector has some advantages, because you can avoid unnecessary resource overhead by setting the initialization size of the collection. The usage mode in ArrayList and Vector queries data from a specified position (through index) or adds or removes an element at the end of the set at the same time, this time is represented by O (1. However, if an element is added or removed from another position in the Set, the time consumed will grow linearly: O (n-I), where n represents the number of elements in the set, I indicates the index location where the element is added or removed. Why? It is assumed that all elements after the I and I elements in the collection must be displaced during the above operations. What does all this mean? This means that you can only search for elements at a specific position or add or remove elements at the end of the set. You can use Vector or ArrayList. For other operations, you 'd better select another set operation class. For example, does the LinkList set class take the same time to add or remove any element from the set? O (1), but it is slow to index an element-O (I), where I is the index position. it is also easy to use ArrayList, because you can simply use indexes instead of creating iterator objects. LinkList also creates an object for each inserted element, and you need to understand that it also brings additional overhead. Finally, in Practical Java, Peter Haggar recommends using a simple Array instead of Vector or ArrayList. This is especially true for programs with high execution efficiency requirements. Array is used to avoid synchronization, additional method calls, and unnecessary Space reallocation. List is an object with a long life cycle, so that it = null list should be used as early as possible, and the Post is null, so that GC can be recycled. otherwise, if too many Object_ I elements exist in the list, the system will surely encounter an OutOfMemory error. list is an interface, while ListArray is a class. ListArray inherits and implements the List. Therefore, the List cannot be constructed, but a reference can be created for the List as above, and ListArray can be constructed. List list; // correct list = null; List list = new List ();//??? It is incorrect usage --------------------------------------------------------------- the two results are different. List list = new ArrayList (); this statement creates an ArrayList object and traces it to List. In this case, it is a List object, and some ArrayList has attributes and methods that are not available in List, so it cannot be reused. While ArrayList list = new ArrayList (); when an object is created, all attributes of ArrayList are retained. This is an example: import java. util. *; public class TestList {public static void main (String [] args) {List list = new ArrayList (); ArrayList arrayList = new ArrayList (); list. trimToSize (); arrayList. trimToSize () ;}compile the code to get the result. --------------------------------------------------------------- If it looks like this: List a = new ArrayList (); then a has all the attributes and methods of List and ArrayList, if the List and ArrayList have the same attributes (such as int I) and have the same method (such as void f (),. I is calling I. f () is the key to calling f (); --------------------------------------------------------------------------- upstairs. Why use List list = new ArrayList () instead of ArrayList alist = new ArrayList? The problem is that List has multiple implementation classes. Now you are using ArrayList. Maybe you need to change to another implementation class on that day, such as struct List or Vector, in this case, you only need to change this line: List list = new sort list (); Other code that uses List does not need to be modified at all. Suppose you start to use ArrayList alist = new ArrayList (), and you have modified it, especially if you use the methods and attributes unique to ArrayList. ------------------------------------------------------------- List is an interface. For interface programming, List = new ArrayList (); this is actually an ArrayList object, but it is transformed to the list type, therefore, the methods that ArrayList does not have in the List cannot be used, but it is still an ArrayList type. Code: List list = new ArrayList (); System. out. println (list. getClass ());

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.