Java Container Classes

Source: Internet
Author: User
Tags comparable

First, Container class:

From the Java programming idea, the structure of the entire container class is well demonstrated.

From the known, the Container class library can be divided into two major categories, each implemented the collection interface and map interface, the following common classes to classify:

Container classes that implement the collection interface

Collection
├list
│├linkedlist
│├arraylist
│└vector
│└stack
├set

│├treeset
│└hashset

└linkedhashset

├queue

│├linkedlist

│├delayqueue
│└priorityqueue

Container classes that implement the map interface

Map
├hashmap

└linkedhashmap

├hashtable

├identityhashmap

├treemap
└weakhashmap

The container class is extended from top to bottom by two first-level interfaces:

    • Collection: A sequence that holds independent elements
    • MAP: A key-value pair element that holds the Key-value type.

It is worth noting that collection provides the iterable () pattern, which can be obtained to iterator the elements within the collection, and the map needs to be collection to get iterator to traverse.

The interface list, set, and queue implements the collection interface, and the corresponding list, set, and queue have their classes implemented. The main implementations of the map interface are HashMap, Linkedhashmap, Hashtable, Identityhashmap, TreeMap, and Weakhashmap.

Second, Implement Collection the container class for the interface

Here is a brief introduction to several common containers under list, set, and queue

2.1 List Interface

Two typical implementations:

    • LinkedList:

The underlying implementation is a linked list, for which the insert and delete operations are highly efficient, while random access to elements is less efficient than ArrayList.

At the same time, because the LinkedList implements the Deque interface, it can also provide a method that is not defined in the list interface, specifically for manipulating the header and footer elements, which can be used as stacks and queues.

    • ArrayList:

The underlying implementation is an array, which is efficient at random access and querying, and less efficient when inserting and deleting operations. In addition, since the underlying implementation is an array, it is necessary to copy the existing data in the current array into the new storage space when the size of the array requires additional storage space.

Two deprecated list implementations:

    • Vector:

Vectors and ArrayList are also implemented by arrays, so their properties are similar to ArrayList (the vector underlying array implementation expands 1 time times when expanding, while ArrayList expands 50%+1), One of the things that deserves special attention is that vector is a thread-safe container in which only one thread can write vectors at a time, avoiding inconsistencies caused by simultaneous writing of multiple threads, but because of the high cost of implementing synchronization (synchronized keyword), the access speed is slower.

    • Stack:

is a subclass of vector that implements a standard LIFO stack. (The ability to implement the stack now typically uses linkedlist)

2.2 Set interface

is a collection that does not contain duplicate elements, and the set allows null elements. The element that joins the set must define the Equals () method to ensure the uniqueness of the object.

Several typical implementations are:

    • Hashset:

The optimization of query efficiency is made by using hash function, which is a set designed for fast searching, and the elements in it must define HASHCODE ();

    • Linkedhashset:

has hashset query speed and internally uses a linked list to maintain the order of elements. Elements must also define the Hashcode () method

    • TreeSet:

Maintains an ordered set (implements the SortedSet interface), the underlying structure is a red-black tree, which can be used to get an ordered sequence from set. Element must implement comparable interface

2.3 Queue Interface:

    • Priorityqueue:

The element that is stored in it needs to implement the comparable interface, which is the definition of its own completion priority

    • Deque:

A two-way queue that can add or remove elements in any paragraph. The LinkedList implements the Deque interface, which can realize the data structure of the queue or stack.

Third, the realization Map the container class for the interface

Map does not inherit the collection interface, it provides a key-to-value mapping, a map cannot contain the same key, each key can only map one value.

Several typical implementations are:

    • Hashtable:

Thread Safety

Any object that is not empty (non-null) can be either a key or a value.

Add data using put (key, value), take out the data using get (key), the time overhead for these two basic operations is constant.

Adjust performance with initial capacity and load factor two parameters. Normally the default load factor 0.75 is a good way to achieve a balanced time and space. Increasing the load factor can save space but the corresponding lookup time will increase, which will affect operations like get and put.

Because the object of key will determine the location of the value corresponding to it by calculating its hash function, any object that is a key must implement the Hashcode and Equeals methods.

    • HASHMAP:

Thread not secure

HashMap and Hashtable are similar, except that HashMap is non-synchronous and allows NULL, that is, null value and null key, but when HashMap is considered collection (values () Method can return collection), and its iterative sub-operation time overhead is proportional to the capacity of the HashMap. Therefore, if the performance of the iterative operation is quite important, do not set the initialization capacity of the hashmap too high, or load factor too low

    • Identityhashmap:

Use the reference "= =" instead of equal when comparing keys (and values). That is, in Identityhashmap, two keys K1 and K2 are considered equal when and only if (K1==K2)

In normal MAP implementations (such as HASHMAP), two keys K1 and K2 are considered equal if and only if the following conditions are true: (K1==null? K2==null:e1.equals (E2))).

This class is applied to specific scenarios where we must use address equality to determine the value of equality, and we determine that as long as its address is not equal, the result of its Equals method must also be unequal.

A good example of this is the Threadlocal class in thread-local storage, which is based on threads getting thread-independent values from their internal map, so when we use a identityhashmap that only determines the equivalent of the address, it will be faster than HashMap.

    • Weakhashmap:
      Weakhashmap is an improved hashmap, which implements a "weak reference" to key, which can be recycled by GC if a key is no longer referenced externally.
    • Concurrenthashmap

Thread-Safe map, unlike HashTable, its thread-safe implementation does not involve synchronous locking, it introduces a "segmented lock" concept, a large map is split into multiple "HashTable" (essentially segment), When multithreading accesses data from different data segments in a container, there is no competition between the threads for locks.

Concurrenthashmap is made up of segment arrays and hashentry array structures. Where segment is a reentrant lock, Hashentry is used to store key-value pairs of data.

Segment is similar in structure to HashMap, and is a structure of arrays and lists. A segment contains an array of hashentry. Each hashentry is an element of a linked list structure. Each segment guard the element in a hashentry, and when it is necessary to modify the data of the Hashentry array, it must first obtain the segment lock corresponding to it.

Third, how to choose the Container class

In the daily development, how to choose the appropriate container class is related to the performance and correctness of the program, so how to choose the appropriate container class is critical.

First, the container class stores a reference to the object, not the object itself. For convenience, a reference to a generic abbreviation object is an object. As mentioned above, different containers store different types of objects and have different methods, or there are differences in efficiency when doing the same thing.

Simply put, we divide the stored objects into two types: element and key value pairs.

Elements typically use container class storage that implements the collection interface. And depending on whether the element is ordered (TreeSet), whether the element is unique (the class that implements the set interface), whether to require thread safety (Vector), the usual operation (ArrayList and LinkedList selection) and other requirements to be screened;

The key-value pair is stored using the container class that implements the map interface, and is based on whether thread safety is required (CONCURRENTHASHMAP), whether it is necessary to release the memory (for memory-optimized Weakhashmap), whether the order is required (TREEMAP), Identityhashmap (Whether you can use = = to replace equals to prompt for efficiency) and so on to filter.

Java Container Classes

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.