Java Collection Overview

Source: Internet
Author: User
Tags bit set bitset cas sorts

This article summarizes all of the Java Collections (Collection). Mainly describes the characteristics and uses of individual collections, and how to convert between different collection types.

Arrays

Arrays are Java-specific. It works well when you know the number of data elements you want to work with. Java.util.Arrays contains a number of practical ways to process data:

Arrays.aslist: Can be converted from Array to List. Parameters that can be used as constructors for other collection types.
Arrays.binarysearch: Quick Find in a sorted or one segment.
ARRAYS.COPYOF: You can use this method if you want to enlarge the array capacity and don't want to change its contents.
Arrays.copyofrange: You can copy an entire array or part of it.
Advanced version of Arrays.deepequals, Arrays.deephashcode:arrays.equals/hashcode, supports operation of sub-arrays.
Arrays.equals: If you want to compare two arrays for equality, you should call this method instead of the Equals method in the Array object (the Equals () method is not overridden in the array object, so this method compares references without comparing the contents). This method aggregates the automatic boxing and parameterless variables of Java 5 to enable a variable to be passed to the Equals () method quickly-so this method compares the type of the object directly to the value in the comparison.
Arrays.fill: Fills the entire array or part of it with a given value.
Arrays.hashcode: Used to calculate its hash value based on the contents of the array (the hashcode () of the array object is not available). This method aggregates the features of the auto-boxing and parameterless variables of Java 5 to enable a variable to be passed to the Arrays.hashcode method quickly-simply passing in the value, not the object.
Arrays.sort: Sorts the entire array or part of an array. You can also use this method to sort an array of objects with a given comparer.
Arrays.tostring: Prints the contents of the array.
You can call the System.arraycopy method if you want to copy the entire array or part of it to another array. This method copies the specified number of elements to the destination array from the location specified in the source array. This is undoubtedly an easy way to do this. (sometimes copying with bytebuffer bulk is quicker.) can refer to this article).

Finally, all the collections can be copied to the array using the t[] Collection.toarray (t[] a) method. It is usually called in this way:

1
Return Coll.toarray (New t[coll.size ()]);
This method allocates a large enough array to store all the collections so that ToArray does not have to allocate space when the value is returned.

Single Thread Collection

This section describes a collection that does not support multithreading. These collections are in the Java.util package. Some of them are available in Java 1.O (now deprecated), most of which are republished in Java 1.4. The enumeration collection is republished in Java 1.5, and all collections since this version support generics. Priorityqueue is also included in Java 1.5. The last version of the non-thread-safe collection schema was Arraydeque, which was also republished in Java 1.6.

List

ArrayList: The most useful list collection implementation. The size of the collection (the first unused element in the array) is stored by an integer number or array. Like all list collections, ArrayList can extend its size when necessary. ArrayList the time cost of accessing elements is fixed. Adding elements at the tail cost is low (for constant complexity), while adding elements at the head is expensive (linear complexity). This is the principle of implementation of the ArrayList--all elements from the angle Mark 0 start one after another caused by the arrangement. That is, each element moves backwards one position from the position of the element to be inserted. The CPU cache-friendly collection is array-based. (It's not very friendly either, because sometimes the array contains the object, so it's just a pointer to the actual object).
Linkedlist:deque implementation: Each node holds a pointer to the previous node and the next node. This means that data access and updates have linear complexity (which is also an optimal implementation, where each operation does not traverse more than half the array, and the element with the highest operating cost is the one in the middle of the array). If you want to write efficient LinkedList code, you can use Listiterators. If you want to implement it with a queue/deque (you just need to read the first and last element)--Consider using Arraydeque instead.
Vector: A arraylist version with the thread synchronization method. Now the ArrayList is replaced with a direct.
Queues/deques

The

Arraydeque:deque is based on arrays (ring buffers) with end-to-end pointers. Unlike LinkedList, this class does not implement the list interface. Therefore, you cannot remove any elements without the end-to-end elements. This analogy linkedlist better because it produces less garbage (the old array is discarded at the time of the expansion).
Stack: A last-in-first-out queue. Do not use in production code, use other deque instead (Arraydeque is better).
Priorityqueue: A priority-based queue. Use the natural order or the set of comparators to sort. His primary property,--poll/peek/remove/element, returns the minimum value of a queue. Not only that, Priorityqueue also implements the Iterable interface, which is not sorted (or in other order) when the queue is iterated. In a collection that needs to be sorted, it is easier to use this queue than other queues such as TreeSet.
Maps

HashMap: The most commonly used map implementation. It just corresponds to a key and a value, and there is no other function. There is a fixed degree of complexity for complex hashcode method,get/put methods.
Enummap: Enumeration type as a map of the key values. Because the number of keys is relatively fixed, the corresponding values are stored internally with an array. Generally speaking, efficiency is higher than hashmap.
HashTable: The synchronized version of the old HashMap, HashMap is also used in the new code.
Identityhashmap: This is a special map version that violates the rules of general map: it uses "= =" to compare references instead of calling Object.Equals to determine equality. This feature makes this collection very useful in the algorithm for traversing charts-it is easy to store processed nodes and related data in Identityhashmap. The
Linkedhashmap:hashmap and LinkedList are combined, and the insertion Order of all elements is stored in LinkedList. This is why iterating over Linkedhashmap entries (entry), keys, and values always follows the order in which they are inserted. In the JDK, this is the largest collection of memory consumed per element.
TreeMap: A red-black tree based on a sorted and guided map of information. Each insertion is sorted by natural order or by a given comparer. This map needs to implement the Equals method and Comparable/comparator. CompareTo need consistency. This class implements a Navigablemap interface: it can have a different entry than the number of keys, you can get the previous or next entry of the key, you can get another map of a certain range of keys (roughly the same as the SQL between operator), and some other methods.
Weakhashmap: This map is typically used in the data cache. It stores keys in WeakReference, which means that if there is no strong reference to the key object, the keys can be reclaimed by the garbage collection thread. The value is saved in a strong reference. Therefore, you want to make sure that no reference is directed from the value to the key or that the value is also saved in the weak reference m.put (key, new WeakReference (value)).
Sets

HashSet: A set implementation based on HashMap. Where all the values are false values (the same object object has the same performance as HashMap. Based on this feature, this data structure consumes more unnecessary memory.
Enumset: The value is set of the enumeration type. Every enum in Java is mapped to a different int. This allows a similar collection structure to be used with bitset--, where each bit is mapped to a different enum. There are two implementations of Enumset, regularenumset--by a single long store (capable of storing 64 enumerated values, sufficient for 99.9% cases), jumboenumset--by long[].
BitSet: a bit set. It is often necessary to consider using Bitset to process a set of dense sets of integers (such as an ID collection that starts with a pre-known number). This class uses long[] to store bits.
Linkedhashmap: Like HashSet, this class is based on LINKEDHASHMAP implementations. This is the only set that keeps the insertion order.
TreeSet: Similar to HashSet. This class is based on a treemap instance. This is the only sort of set in the Single threaded section.
Java.util.Collections

Just as there are special java.util.Arrays to handle arrays, there are java.util.Collections in Java to handle collections.

The first set of methods primarily returns the various data for a collection:

Collections.checkedcollection/checkedlist/checkedmap/checkedset/checkedsortedmap/ Checkedsortedset: Checks the type of element to be added and returns the result. Any attempt to add a variable of an illegal type throws a ClassCastException exception. This feature prevents errors at run time. Fixme
Collections.emptylist/emptymap/emptyset: Returns a fixed empty collection and cannot add any elements.
Collections.singleton/singletonlist/singletonmap: Returns a Set/list/map collection with only one entry.
Collections.synchronizedcollection/synchronizedlist/synchronizedmap/synchronizedset/synchronizedsortedmap/ Synchronizedsortedset: Gets the thread-safe version of the collection (multithreaded operations are inexpensive but inefficient, and do not support compound operations such as put or update)
Collections.unmodifiablecollection/unmodifiablelist/unmodifiablemap/unmodifiableset/unmodifiablesortedmap/ Unmodifiablesortedset: Returns an immutable collection. You can use this method when you include a collection in an immutable object.
in the second set of methods, some of these methods are not joined to the collection for some reason:

Collections.addall: Adds some elements or the contents of an array to the collection.
Collections.binarysearch: The Arrays.binarysearch function of the array is the same.
Collections.disjoint: Check that two collections are not the same element.
Collections.fill: Replaces all elements in the collection with a specified value.
Collections.frequency: How many elements in the collection are the same as the given element.
Collections.indexofsublist/lastindexofsublist: is similar to the String.IndexOf (string)/LastIndexOf (String) Method-- Finds the first occurrence or the last occurrence of a child table in a given list.
Collections.max/min: Finds the largest or smallest element in a collection based on natural order or comparer ordering.
Collections.replaceall: Replaces an element in the collection with another element.
Collections.reverse: Reverses the order in which elements are arranged in the collection. If you want to use this method after sorting, it is best to use the Collections.reverseorder comparator when sorting the list.
Collections.rotate: Rotates the element based on a given distance.
Collections.shuffle: Randomly discharges a node in the list collection, given your own generator-for example, java.util.random/java.util.threadlocalrandom or Java.security.SecureRandom.
Collections.sort: Sorts the collection in either a natural order or a given order.
Collections.swap: Swaps the positions of two elements in the collection (most developers do this themselves).
Concurrent Collections

This section describes the collection of thread-safe threads in the Java.util.concurrent package. The primary properties of these collections are an indivisible method that must be performed. Because concurrent operations, such as Add or update or check and update, have more than one call and must be synchronized. Because the first step of combining operations from the collection is queried for information that may become invalid when you start the second step.

The majority of concurrent collections are introduced in Java 1.5. Concurrentskiplistmap/concurrentskiplistset and Linkedblockingdeque are newly added in Java 1.6. Java 1.7 joins the final Concurrentlinkeddeque and LinkedTransferQueue

Lists

Copyonwritearraylist:list implementations each update produces a new, implicitly-array copy, so this is a costly operation. Typically used in a collection where the traversal operation is more than the update operation, such as the Listeners/observers collection.
Queues/deques

Arrayblockingqueue: An array-based implementation of a bounded blocking team, size cannot be redefined. So when you try to add elements to a full queue, you are blocked until another method takes the elements out of the queue.
Concurrentlinkeddeque/concurrentlinkedqueue: An unbounded queue based on a linked list that adds elements that are not blocked. But this requires that the set of consumers work at least as fast as the production, or the memory will be exhausted. Heavily dependent on CAS (compare-and-set) operations.
Delayqueue: The collection of delayed elements that are stored unbounded. The element is removed only when the delay has expired. The first element of the queue is the least deferred (contains a negative value-the delay has expired). Use when you want to implement a queue of deferred tasks (do not manually implement it yourself-using scheduledthreadpoolexecutor).
Linkedblockingdeque/linkedblockingqueue: You can select bounded or unbounded based on the implementation of a linked list. Use reentrantlock-s in cases where the queue is empty or full.
LinkedTransferQueue: A linked-list-based unbounded queue. In addition to the usual queue operations, it has a series of transfer methods that allow the producer to pass information directly to the waiting consumer so that the element is not stored in the queue. This is a non-lock collection based on CAS operations. The unbounded version of the
Priorityblockingqueue:priorityqueue.
Synchronousqueue: A bounded queue with no memory capacity. This means that any insert operation must wait for the response to be fetched before execution, and vice versa. If the queue interface is not required, the function of the response can also be done through the Exchanger class.
Maps

Concurrenthashmap:get operation full concurrency access, put operation can configure a hash table for concurrent operations. The level of concurrency can be set by the Concurrencylevel parameter in the constructor (default Level 16). This parameter divides some partitions within the map. Only the updated partition is locked during a put operation. This map is not a thread-safe alternative to HashMap-any get-then-put operation needs to be externally synchronized.
Concurrentskiplistmap: The Concurrentnavigablemap implementation based on the Skip list. Essentially, this collection can be used as a treemap thread-safe version.
Sets

Concurrentskiplistset: Use Concurrentskiplistmap to store the thread-safe set.
Copyonwritearrayset: Use Copyonwritearraylist to store the thread-safe set.

Java Collection Overview

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.