A collection of Java Foundation enhancement

Source: Internet
Author: User

Set whole frame diagram

Overview of each collection framework

1. Collection (common list and set, not commonly used for queue and vector), single element collection.

2. Map (common HashMap and TreeMap, infrequently used hashtable), Key-value mapping relationship.

3. Iterator (iterator)

4. Comparable and comparator comparators

5. Collections and Arrays Tool classes

Comparison of associative and array in Java

1. The length of the array is specified at initialization, and only the fixed-length data can be saved.

The collection can hold data of indeterminate length. You can also save data that has a mapping relationship (that is, associative arrays, key-value pairs Key-value).

2. A data element can be either a base type value or an object, and the collection can only hold objects (in effect, only reference variables of the object), and variables of the base data type are converted to the corresponding wrapper class in order to be placed in the collection.

General collection features Overview list system

List features: elements are placed in order, elements can be repeated .

The three implementation classes of the list interface: ArrayList, LinkedList, and vector.

The difference between ArrayList, linkedlist and vectors

LinkedList: The underlying is based on the linked list implementation, the linked list memory is scattered, each element stores its own memory address and also stores the memory address of the next element. link list and delete fast, find slow.

ArrayList and vectors: The bottom of both are based on the implementation of the array, query fast, adding and deleting slow. the difference between the two is that ArrayList is thread-insecure and efficient, while vectors are thread-safe and inefficient.

The initialization size of the ArrayList is 10, and the expansion strategy is 1.5 times times the size of the original element number.

Selection criteria

If the "Dynamic array", "stack", "queue", "linked list" and other structures, should consider the list, specifically select which list implementation class, according to the following criteria to choose:

1. You should use LinkedList for quick insertion and deletion of elements.

2. For fast random access to elements, you should use ArrayList.

3. For a "single-threaded environment" or "multithreaded environment, but the list will only be operated by a single thread", a non-synchronized class (such as ArrayList) should be used. For a multithreaded environment, and the list may be manipulated by more than one thread at a time, you should use a synchronized class (such as a vector).

Set System

Set features: elements are placed in no order and elements cannot be duplicated.

Three implementation classes for the set interface: Linkedset, HashSet, and Linkedhashset.

HashSet (the bottom layer is implemented through HASHMAP) The bottom layer is weighed down by hashcode and equals.

HashSet the elements of a set are equal

The comparison of two objects is divided into the following four cases:
1. If there are two elements that return false through the equal () method, and their hashcode () methods return unequal, HashSet will store them in a different location.

2. If there are two elements that return true through the equal () method, but their hashcode () methods return unequal, HashSet will store them in a different location.

3. If two objects are not equal through the Equals () method, but the Hashcode () method is more equal, HashSet will store them in the same location, where multiple objects are stored in a linked-list structure. This is because when an element is deposited into the HashSet collection, HashSet invokes the Hashcode () method of the object to get the Hashcode value of the object, and then, based on that hashcode value, determines where the object is stored in HashSet.

4. If there are two elements that return true through the equal () method, and their hashcode () method returns True,hashset will not be added.

HashSet determines the criteria for equality of two elements: two objects are compared by the Equals () method and the Hashcode () method return values for two objects are equal.

Note: HashSet is quickly positioned based on the hashcode value of the element , and if more than two elements in HashSet have the same hashcode value, this can result in performance degradation. Therefore, if you override the Equals () method and the Hashcode () method of a class, you should try to ensure that two objects return true by using the Equals () method when the value is equal by the Hashcode () method.

Linkedhashset class

Linkedhashset is a subclass of hashset pairs, and also determines where elements are stored based on their hashcode values, while maintaining the order of elements using linked lists, so that elements are saved in the order in which they are inserted. When iterating through the elements in the Linkedhashset collection, Linkedhashset will access the elements in the collection in the order in which they are added. However, due to maintaining the insertion order of the elements, the performance is slightly lower and hashset, but there is good performance in iterating through all the elements of the set.
Note: Linkedhashset still does not allow elements to repeat, judging the repetition criteria to be consistent with HashSet.

Add:The essence of HashSet is a hashmap. all of the collection elements of the HashSet form the HashMap key, whose value is a static object object . so all the properties of HashSet, the set of HashMap key, are available. You can refer to the relevant content of HashMap in the following article for comparison.

TreeSet class

TreeSet is an implementation class for the SortedSet interface, as the SortedSet name implies, TreeSet can ensure that the collection element is in the sorted state. In addition, TreeSet provides several additional methods.

1 Comparator (): Returns a comparer that sorts the elements in this set and returns NULL if this set uses the natural order of its elements. 2 First (): Returns the current (lowest) element in this set. 3 last (): Returns the current (highest) element in this set. 4Lower (E): Returns the largest element in this set that is strictly less than the given element, or returns if no such element exists.NULL. 5Higher (E): Returns the smallest element in this set that is strictly greater than the given element, or returns if no such element exists.NULL. 6 subset (e fromelement, E toelement): Returns a partial view of this set whose elements are from fromelement (including) to Toelement (not included). 7 HeadSet (E toelement): Returns a partial view of this set whose elements are less than toelement. 8Tailset (E fromelement): Returns a partial view of this set whose elements are greater than or equal to fromelement.

Map Department

Map features: The stored element is a key-value pair, in the JDK1.8 version is node, in the old version is entry.

The map interface has four implementation classes: HashMap, HashTable, Linkedhashmap, and Concurrenthashmap.

HashMap class

HashMap is a non-thread-safe, efficient, null-enabled key and value, and the underlying implementation is an array and a linked list, with the Hashcode method and the Equals method guaranteeing the uniqueness of the key.

There are two ways to use a thread-safe map If you need to:

1. Using Hashtable

2. Use Collections.synchronizedmap (HASHMAP) mode for synchronization.

There are three main ways to resolve conflicts: addressing, zipper and re-hashing.

HashMap is to use the Zipper method to solve the conflict, the Zipper method is the same hash value of the object into a list placed in the hash value corresponding to the slot.

The initialization size of the HashMap is 16, the expansion factor is 0.75, and the expansion strategy is twice times the size of the original capacity.

the approximate process of put

1. Calculate the hash value of key by Hashcode method

2. The index stored in table is calculated by Hash%length (hash& (length-1) is used in the source code, so the result is the same, but faster).

3. If the value of Table[index] is empty then it is stored directly, and if it is not empty then it is linked to the head of the linked list where the number is located. (In JDK1.8, if the list length is greater than 8, it turns into a red-black tree)

approximate process of Get

1. Calculate the hash value of key by using the Hashcode method

2. The index stored in table is calculated by Hash%length (hash& (length-1) is used in the source code, so the result is the same, but faster).

3. Traverse Table[index] is the linked list, only if the key and the value of the key in the node is not taken out at the same time.

Concurrenthashmap class

is a Hashtable alternative implementation from JDK1.5, using a segmented lock mechanism, a map of the elements into a lot of segment, through the lock mechanism can be added to each segment read and write locks, thereby improving the efficiency of the map, the underlying implementation using array + linked list + The storage structure of the red-black tree.

Hashtable class

Thread-safe, inefficient, null-not-supported key and value.

SortedMap class

There is an implementation class: TreeMap stores the order in which the elements are placed.

A collection of Java Foundation enhancement

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.