First, let's take a look at the relationship between them.
Collection InterfaceObject set
Shortlist Sub-interface Save in sequenceRepeatable
│ Invalid parameter list Interface implementation classLinked ListInsert and deleteNo SynchronizationThread Security
│ ├ Arraylist Interface implementation classArrayRandom AccessNo SynchronizationThread Security
│ Vector Interface implementation classArray Synchronization Thread Security
│ Elastic Stack
Sorted set Sub-interface Receive only once and perform internal sorting
├ Hashset
│ └ Linkedhashset
└ Treeset
For list, the focus is on order, which ensures that the specific sequence of elements is maintained (the same element is allowed). This interface can be used to precisely control the insert position of each element. You can use indexes (the position of an element in the list, similar to the array subscript) to access the elements in the list.
For a set, you only care about whether an element belongs to the Set (the same element is not allowed), but about its sequence.
Map Interface Set of key-value pairs
├ Hashtable Interface implementation class Synchronization
Thread Security
├ Hashmap Interface implementation class No Synchronization Thread Security
│ ├ Linkedhashmap
│ └ Weakhashmap
├ Treemap
└ Identifyhashmap
The biggest feature of map is key-value ing, which is a one-to-one ing. Keys cannot be repeated and values can be used. Therefore, keys are used to index values. The put (Object key, object Value) method adds a "value" (desired) and a "key" (key) associated with the "value" (use it for search ). The get (Object key) method returns the "value" associated with the given "key ".
MAP also saves a copy of each element, but this is based on the "key". MAP also has built-in sorting, so it does not care about the order of element addition. If the order of adding elements is important to you, you should use linkedhashset or linkedhashmap.
For efficiency, because map uses Hash hash, It is faster to search for elements than arraylist.
A more refined summary:
Collection is a collection of objects. Collection has two subinterfaces: List and set.
List can be obtained through subscript (1, 2 ..), the value can be repeated
The set value can only be set through the cursor, and the value cannot be repeated.
Arraylist, vector, and aggregate list are implementation classes of list.
Arraylist is thread-insecure, and vector is thread-safe. The underlying layers of these two classes are implemented by arrays.
The producer list is thread unsafe, and the underlying layer is implemented by the linked list.
Map is a set of key-value pairs.
Hashtable and hashmap are map implementation classes.
Hashtable is thread-safe and cannot store null values.
Hashmap is NOT thread-safe and can store null values.
1. List Interface
List is an ordered collection, and order is the most important feature of list: it ensures that the specific order of elements is maintained. 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. Among them, the most commonly used are 'arraylist' and 'arraylist.
Sort list class
The listlist interface allows null elements. In addition, the extended list provides additional addfirst (), addlast (), getfirst (), getlast (), removefirst (), removelast (), insertfirst (), insertlast () methods are at the beginning or end of the queue list. These methods (not defined in any interface or base class) 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 (newdetaillist (...));
Features: sequential access is optimized, and the overhead of insert and delete to the list is not large. Random Access is relatively slow. (Use arraylist instead .)
Arraylist class
Arraylist is a list implemented by arrays and an array of variable sizes is implemented. 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 ).
Features: quick and Random Access to elements is allowed, but the process of inserting and removing elements into the list is slow. Listiterator should only be used to traverse the arraylist from the forward, rather than to insert and remove elements. This is much higher than the overhead of the shortlist.
Vector
The vector is very similar to the 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 vector State (for example, adding or deleting some elements). When calling the iterator method, concurrentmodificationex will be thrown.Ception, so the exception must be caught.
Stack class: the stack inherits 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.
2. Set Interface
Set has the same interface as collection, so there is no additional function, unlike the previous several different lists. Set is actually a collection, but the behavior is different. (This is a typical application of inheritance and Polymorphism: different behavior ). Second, set is a collection that does not contain repeated elements. The elements added to the set must define equals () method To ensure the uniqueness of the object (I .e., the two elements E1 and E2 both have e1.equals (E2) = false). Unlike list, the set interface does not guarantee the order of elements. Finally,
Set 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.
Hashset class
Set designed for quick search. The object stored in the hashset must define hashcode ().
Linkedhashset class: query speed with hashset, and internal use of the linked list to maintain the order of elements (insert order ). When you use the iterator to traverse the set, the result is displayed in the order of element insertion.
Treeset class
The set that stores the order. The underlying layer is the tree structure. It can be used to extract ordered sequences from the set.
Ii. Map Interface
Note that map does not inherit the collection interface. Map provides a key ing between key and value. You can use the "key" to find the "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 put (Object key, object Value) method adds a "value" (desired) and a "key" (key) associated with the "value" (use it for search ). The get (Object key) method returns the "value" associated with the given "key ". You can use containskey () and containsvalue () to test whether a map contains a "key" or "value ". The standard Java class library contains several different maps: hashmap, treemap, linkedhashmap, weakhashmap, and identityhashmap.
. They all have the same basic interface map, but the behavior, efficiency, sorting policy, saving object lifecycle and determining "key" equivalent policies are different.
MAP also saves a copy of each element, but this is based on the "key". MAP also has built-in sorting, so it does not care about the order of element addition. If the order of adding elements is important to you, you should use linkedhashset or linkedhashmap.
Execution efficiency is a big problem of map. Let's look at what get () is going to do, and we will understand why searching for "keys" in arraylist is quite slow. This is where hashmap improves the speed. Hashmap uses a special value called "hashcode" to replace the slow key-to-key search. The "hash code" is a "relatively unique" used to represent the int value of an object. It is generated by converting certain information of the object (in the following summary: further discussion is required ). All Java objects can generate hash codes, because hashcode () is a method defined in the base class object.
Hashmap uses the hashcode () of an object for quick query. This method can significantly improve the performance.
Hashtable class
Hashtable 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 adjusts the performance by initial capacity and load factor. Generally, the default loadfactor 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", and "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 );
As the key object is determined by calculating its hash function, any object used as the key must implement the hashcode method and equals method. The hashcode and equals Methods inherit from the root class object. If you use a custom class as the key, be 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
Similarly, this phenomenon is called a conflict. A conflict will increase the time overhead for operating the hash table. Therefore, we recommend that you define the hashcode () method 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.
Hashmap class
Like hashtable, hashmap is also implemented based on hash. The difference is that hashmap is non-synchronous and allows null, that is, null value and null key. When hashmap is treated as a collection (the values () method can return the collection), the overhead of inserting and querying "key-value pairs" is fixed, however, the time overhead of its iteration sub-operations is proportional to the capacity of hashmap. Therefore, if the performance of iterative operations is very important, do not set the hashmap initialization capacity (initial capacity) too high or load factor
(Load factor) is too low.
Linkedhashmap class: similar to hashmap, but when traversing it iteratively, the order in which "key-value pairs" are obtained is the insertion order, or the least recently used (LRU) Order. It is only a little slower than hashmap. It is faster during iterative access because it uses the linked list to maintain the internal order.
Weakhashmap class: weak Key Map is an improved hashmap designed to solve special problems. It implements "weak reference" for keys ", if a key is no longer referenced outside of the map, it can be recycled by the garbage collector (GC.
Treemap class
The implementation is based on the data structure of the red and black trees. When you view "keys" or "key-value pairs", they are sorted (the order is determined by comparabel or comparator ). Treemap features that the results you get are sorted. Treemap is the only map with submap () method. It can return a subtree.
Identifyhashmap class
Use = to replace the hash map used by equals () to compare the "key. Designed to solve special problems.
Conclusion 1: Comparison
1. Array (array), array class (arrays)
Array is the most efficient method for Java's "Storage and random access to a series of objects. However, the disadvantage is that the capacity is fixed and cannot be changed dynamically. Another disadvantage of array is that it cannot determine the actual number of elements in the array. length only tells us the array capacity.
Java has an array class (arrays) which is used to operate arrays. An array class (arrays) has a set of static functions.
Equals (): checks whether two arrays are equal. Array has the same number of elements, and all corresponding elements are equal to each other.
Fill (): Enter the value in array.
Sort (): used to sort arrays.
Binarysearch (): Search for elements in the sorted array.
System. arraycopy (): copying an array.
If you do not know how many objects are needed when writing a program and need to automatically expand the capacity when the space is insufficient, you need to use the container class library. array is not applicable.
2. Differences between container classes and Arrays
The container class can only hold the object reference (pointer to the object), instead of copying the object information to a certain position in the series. Once an object is placed in a container, the type information of the object is lost.
3. Relationships and differences between containers (collections) and map
Collection type, each location has only one element.
Map type, holding a key-Value Pair (pair), like a small database.
Collections is a help class for the Collection class. Provides a series of static methods for searching, sorting, and thread-based operations on various sets. It is equivalent to arrays, a class that performs similar operations on arrays.
For example, collections. Max (Collection Coll); obtains the largest element in Coll.
Collections. Sort (list); sorts the elements in the list.
List, set, and map are regarded as object types.
Collection, list, set, and map are all interfaces and cannot be instantiated. The arraylist, vector, hashtable, and hashmap inherited from them are concrete classes, which can be instantiated.
The vector container knows exactly the type of the object it holds. Vector does not perform boundary check.
Conclusion 2: Notes
1. Collection can only traverse elements through iterator () without the get () method.
2. Set and collection have the same interface. However, the elements that pass in the collection parameter are excluded.
3. list. You can use the get () method to retrieve an element at a time. Use numbers to select one of a bunch of objects, get (0 ).... (Add/get)
4. Map uses put (K, v)/get (K) and containskey ()/containsvalue () to check whether a key/value exists.
Hashmap uses the hashcode of the object to quickly find the key.
Hashing refers to converting the object information to form a unique int value, which is stored in an array. We all know that the array search speed is the fastest in all storage structures. Therefore, the search can be accelerated. When a collision occurs, let the array point to multiple values. That is, an orders table is generated at each position of the array.
5. Elements in map can be extracted separately from the key sequence and value sequence.
Use keyset () to extract the key sequence and generate a set for all the keys in the map.
Use values () to extract the value sequence and generate a collection for all values in the map.
Why does one generate a set and one generate a collection? That's because the key is always unique and the value can be repeated.
Conclusion 3: How to choose
From the efficiency perspective:
In various lists, for elements that need to be quickly inserted or deleted, use the shortlist (stack and queue can be constructed using the shortlist). If you need to quickly and randomly access elements, use the arraylist. The best practice is to use arraylist as the default choice. Vector is always slower than arraylist, so avoid using it whenever possible.
In various sets, hashset is generally better than hashtree (insert and search ). Treeset is used only when a sorted sequence is generated. The only reason for the existence of hashtree is that it can maintain the sorting status of its elements.
In various maps, hashmap is used for quick search.
Finally, when the number of elements is fixed, array is used because array is the most efficient.
Conclusion: arraylist, hashset, hashmap, and array are commonly used.
Further analysis:
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. As the key object, the equals method and hashcode method should be correctly rewritten at the same time.
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.
Http://blog.sina.com.cn/s/blog_67d81e6a0100kzfq.html