Java Improvement Chapter (20)-----Collection Big Family

Source: Internet
Author: User
Tags set set

In the Java program, we most commonly used in addition to eight basic data types, the string object has a collection class, in our program is filled with the collection of the figure! The collection of large family members in Java is too rich, there are commonly used ArrayList, HASHMAP, HashSet, there are not commonly used stack, Queue, wired safe vector, HashTable, but also wired unsafe linkedlist , TreeMap and so on!

The diagram above shows the members of the entire collection and the relationships between the large families. Here are the above interface, the base class to do some simple introduction (mainly introduces the characteristics of each collection. The more detailed introduction will be explained in the near future one by one.

First, collection interface

Collection interface is the most basic collection interface, it does not provide a direct implementation, the Java SDK provides classes are inherited from the collection "sub-interface" such as list and set. Collection represents a rule that contains elements that must follow one or more rules. If some are allowed to repeat while others cannot be duplicated, some must be inserted sequentially and some are hashed, some support sorting but others do not.

All classes in Java that implement the collection interface must provide two standard constructors, one without parameters, to create an empty collection, and a parameter constructor with collection parameters for creating a new collection. This new collection has the same elements as the incoming collection.

Second, List interface

The list interface is a direct interface to the collection. The list represents an ordered collection, which maintains the order of elements in a particular order of insertion. The user can precisely control where each element in the list is inserted, and can access the element based on the integer index of the element (in the list) and search for the elements in the list. The implementation of the list interface collection mainly includes: ArrayList, LinkedList, Vector, Stack.

2.1, ArrayList

ArrayList is a dynamic array and is the most common collection we use. It allows any element that conforms to the rule to be inserted even including null. Each ArrayList has an initial capacity (10), which represents the size of the array. As the elements in the container continue to increase, the size of the container increases as well. A capacity check is carried out each time an element is added to the container, and the expansion is performed when the overflow is fast. So if we are clear about the number of elements inserted, it is better to specify an initial capacity value , to avoid excessive expansion operations and waste time, efficiency .

Size, IsEmpty, get, set, iterator, and listiterator operations are all run at a fixed time. The add operation runs at the allocated fixed time, that is, adding n elements requires an O (n) time (because of the expansion, this is not just adding elements that can be as simple as allocating fixed-time overhead).

ArrayList specializes in random access. At the same time ArrayList is not synchronous.

2.2, LinkedList

The same implementation of the list interface LinkedList and ArrayList different, ArrayList is a dynamic array, and LinkedList is a doubly linked list. So it provides an additional Get,remove,insert method at the first or the end of the LinkedList in addition to the basic operating method of the ArrayList.

Due to the way the implementation is different, LinkedList cannot be accessed randomly, and all of its operations are performed according to the needs of the doubly linked list. An operation indexed in a list traverses the list from the beginning or end (from one end near the specified index). The advantage of this is that you can insert and delete operations in the list at a lower cost.

As with ArrayList, LinkedList is also unsynchronized. 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 (...));

2.3. Vector

Similar to ArrayList, but vectors are synchronous. So vector is a dynamic array of thread safety. It operates almost the same as ArrayList.

2.4. Stack

Stack inherits from Vector and implements a last-in-first-out stack. The stack provides 5 additional ways to make the vector available as a stack. The basic push and pop methods, and the Peek method to get the stack top element, the empty method tests if the stack is empty, and the search method detects the position of an element on the stack. Stack has just been created as an empty stack.

Third, set interface

Set is a collection that does not include duplicate elements. It maintains its own internal ordering, so random access doesn't make any sense. As with list, it also runs NULL, but only one. Because of the particularity of the set interface, all elements in the incoming set set must be different, and it is important to note that any mutable object that causes E1.equals (E2) ==true when manipulating elements in the collection is bound to produce some problems. The set interface is implemented with the following sets: Enumset, HashSet, TreeSet.

3.1, Enumset

Is the private set of the enumeration. All the elements are enumerated types.

3.2, HashSet

HashSet is the fastest collection of queries because it is internally implemented with Hashcode. The order of its inner elements is determined by the hash code, so it does not guarantee the set's iteration order, especially because it does not guarantee that the order will be constant.

3.3, TreeSet

Based on TreeMap, a set is generated that is always in the sorted state, and is implemented internally with TreeMap. It is ordered by using the natural order of the elements, or by the sort provided when the set is created Comparator , depending on the construction method used.

Four, Map interface

Unlike the list and set interfaces, a map is a collection of key-value pairs that provide a key-to value mapping. At the same time it did not inherit collection. In map it guarantees a one by one correspondence between key and value. This means that a key corresponds to a value, so it cannot have the same key value, but the value can be the same. The implementation map has: HashMap, TreeMap, HashTable, Properties, Enummap.

4.1, HashMap

Implemented in a hash table data structure, the location of the object is computed by a hash function, which is designed for fast querying, which defines an array of hash tables (entry[] table), which converts the hash address of an element into an index stored in a group by a hash conversion function, if there is a conflict, A hash list is used to string all elements of the same hash address, possibly by looking at the source of the Hashmap.entry, which is a single-linked list structure.

4.2, TreeMap

The key is sorted by some sort rule, the internal red-black (red-black) tree data structure is implemented, and the SortedMap interface is implemented.

4.3, HashTable

is also in the form of hash table data structure, conflict resolution and HashMap is also used as a hash list, but the performance is lower than the HashMap

V. Queue

Queue, it is divided into two major categories, one is the blocking queue, the queue full after the insertion of elements will throw an exception, mainly including Arrayblockqueue, Priorityblockingqueue, Linkedblockingqueue. The other is a double-ended queue, which supports inserting and removing elements at both ends of the head and tail, mainly including: Arraydeque, Linkedblockingdeque, LinkedList.

Vi. Similarities and differences

Source: http://blog.csdn.net/softwave/article/details/4166598

6.1. Vector and ArrayList

1,vector is thread-synchronized, so it is thread-safe, and ArrayList is thread-asynchronous and unsafe. If the thread security factors are not taken into account, the ArrayList efficiency is generally higher.
2, if the number of elements in the collection is greater than the length of the current collection array, the vector growth rate is 100% of the current array length, while the ArrayList growth rate is 50% of the current array length. If you use data with larger data volumes in a collection, vector has some advantages.
3, if you look for a specified location of data, the vector and ArrayList use the same time, are 0 (1), this time using both vector and ArrayList can be. If moving a data at a specified location takes 0 (n-i) n for the total length, this should take into account the use of linklist, since it takes 0 (1) to move the data at a specified location, and the time to query the data at a specified location is 0 (i).

ArrayList and vectors use arrays to store data, which is larger than the actual stored data in order to add and insert elements, allowing direct ordinal index elements, but inserting data to design memory operations such as array element movement, so the index data is fast inserting data slowly, Vector because of the use of the Synchronized method (thread safety) so the performance is worse than the ArrayList, LinkedList using the two-way linked list to implement storage, indexed by ordinal data needs to be traversed forward or backward, but when inserting data only need to record the item's front and rear items, So insert several faster!

6.2, A ArrayList and LinkedList

1.ArrayList is the realization of the data structure based on dynamic array, LinkedList data structure based on linked list.
2. For random access get and set,arraylist feel better than LinkedList, because linkedlist to move the pointer.
3. Add and Remove,linedlist are the dominant for new and deleted operations because ArrayList is moving the data.
This point depends on the actual situation. If you insert or delete only a single piece of data, the ArrayList speed is better than LinkedList. But if bulk random insert deletes data, LinkedList speed is much better than ArrayList. Because ArrayList each insertion of data, you move the insertion point and all subsequent data.

6.3, HashMap and TreeMap

1, HashMap through the hashcode of its content to quickly find, and treemap all the elements are kept in a fixed order, if you need to get an ordered result you should use TREEMAP (the order of the elements in HashMap is not fixed). The order of the elements in the HashMap is not fixed.

2, HashMap through the hashcode of its content to quickly find, and treemap all the elements are kept in a fixed order, if you need to get an ordered result you should use TREEMAP (the order of the elements in HashMap is not fixed). The collection framework provides two general map implementations: HashMap and TreeMap (TreeMap implements the SortedMap interface).

3, inserting, deleting and locating elements in map, HashMap is the best choice. But if you want to traverse the key in natural order or in a custom order, TreeMap is better. The implementation of Hashcode () and Equals () is clearly defined by the key class that is required to be added using HashMap. There is no tuning option for this treemap because the tree is always in a balanced state.

6.4, Hashtable and HashMap

1, historical reason: Hashtable is based on the old dictionary class, HashMap is an implementation of the map interface introduced by Java 1.2.

2, synchronization: Hashtable is thread-safe, that is, synchronous, and HashMap is a line program is not secure, not synchronous.

3. Value: Only HashMap can let you use NULL as the key or value of an entry for a table.

Vii. selection of the set7.1, the selection of the list

1. For random queries and iterative traversal operations, arrays are faster than all containers. So the general use of ArrayList in random access

2. LinkedList uses a doubly linked list to provide very good support for adding and deleting elements, while ArrayList execution adds and removes elements that require element displacements.

3, for vector only, we generally are to avoid the use.

4, the ArrayList as the first choice, after all, for the collection of elements we are all traversing, only when the performance of the program because the list of frequent insertion and deletion of the lower, and then consider the LinkedList.

7.2, the choice of set

1, hashset because of the use of hashcode implementation, so in some way its performance is always better than treeset, especially to increase and find operations.

3, although TreeSet does not have a good hashset performance, but because it can maintain the ordering of elements, so it still exists.

7.3, the choice of map

1, HashMap and HashSet same, support fast query. Although the speed of Hashtable speed is not slow, but in front of hashmap still slightly slower, so hashmap in the query can replace Hashtable.

2, because treemap need to maintain the order of internal elements, it is usually slower than HashMap and Hashtable.

personal website: cmsblogs

Java Improvement Chapter (20)-----Collection Big Family

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.