Java collections Framework defines, operates, and manages a set of interfaces and class architectures. Java Collection framework basic interface/class hierarchy: Java. util. Collection [I]
+ -- Java. util. list [I]
+ -- Java. util. arraylist [c]
+ -- Java. util. Collections list [c]
+ -- Java. util. Vector [c]
+ -- Java. util. Stack [c]
+ -- Java. util. Set [I]
+ -- Java. util. hashset [c]
+ -- Java. util. sortedset [I]
+ -- Java. util. treeset [c] java. util. Map [I]
+ -- Java. util. sortedmap [I]
+ -- Java. util. treemap [c]
+ -- Java. util. hashtable [c]
+ -- Java. util. hashmap [c]
+ -- Java. util. linkedhashmap [c]
+ -- Java. util. weakhashmap [C] [I]: interface [c]: Class
Collection Interface
Collection is the most basic collection interface. A collection represents a collection of objects called collection elements. 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. The typical usage is as follows:
- Iterator it = collection. iterator (); // obtain an iterator
- While (it. hasnext ()){
- Object OBJ = it. Next (); // obtain the next element.
- }
Collection is divided into list and set based on different purposes.
List InterfaceList inherits from the collection 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 set, list allows repeated elements. Elements of E1 and E2 objects that meet the e1.equals (E2) conditions can exist in the list set at the same time. Of course, there are also list implementation classes that do not allow repeated elements. 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.
Sort list classThe listlist interface allows 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 collections list (...));
Arraylist classArraylist 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 ).
VectorThe 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 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.
StackStack inherits from 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 include the peek method to get the elements at 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.
Set InterfaceSet inherits from the collection interface. Set is a set that cannot contain repeated elements. For E1 and E2 object elements that meet the e1.equals (E2) conditions, they cannot exist in the same set at the same time. In other words, any two elements of the Set, E1 and E2, meet the conditions of e1.equals (E2) = false. A set can have a maximum of null elements. Due to this restriction of set, when using the set, Note: 1. implement an effective equals (object) method for the Implementation class of elements in the Set set. 2. For the set constructor, the imported collection parameter cannot contain duplicate 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 classThis set interface is supported by a hash table (actually a hashmap instance. It does not guarantee the iteration sequence of the Set; in particular, it does not ensure that the order remains unchanged. This class allows the use of null elements. Hashset is not synchronous. You need to use the following statement for S synchronous conversion:
Set S = collections. synchronizedset (New hashset (...));
Map InterfaceMap does not inherit the collection interface. That is to say, MAP and collection are two different sets. Collection can be seen as a set of values, while map can be seen as a set of (Key, value. The map interface provides three types of set views by map content, one set of keys, one set of values, or one set of key-value ing relationships.
Hashtable classHashtable 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", 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 and equals method. 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.
Hashmap classHashmap 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 classWeakhashmap 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.
Tool class for Set OperationsJava provides Java. util. Collections and Java. util. arrays classes to simplify collection operations.
Java. util. Collections mainly provides some static methods to operate or create collection, map and other sets.
Java. util. arrays mainly provides the static method for Array Operations ..
SummaryIf 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 random 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. Hashset and hashmap should be used in addition to treeset and treemap for sorting, because they are more efficient. Pay special attention to the operations on the hash table. The equals and hashcode methods should be correctly rewritten as the key object. 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. 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.
Note:1. collection does not have the get () method to obtain an element. You can only use iterator () to traverse elements. 2. Set and collection have the same interface. 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. arraylist is generally used. Use the queue list to construct the stack and queue. 5. 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. 6. 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. ------------------------ This article combines several online articles and extracts them: 1. java collections framework-Java Collection framework list, MAP, set, etc. java util Class 3. java basic concepts: Collection class list/set/map... differences and connections