Java Collection Overview

Source: Internet
Author: User
Tags bit set bitset cas deprecated 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.Arrayscontains 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 do not want to change its contents.
    • Arrays.copyofrange: You can copy an entire array or a subset of them.
    • arrays.deepequals , arrays.deephashcode: arrays.equals/hashcode Advanced version, 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 content). This method aggregates the features of the auto-boxing and parameterless variables of Java 5 to enable a variable to be passed to   quickly; equals ()   Method-so this method compares the type of the object directly after it is passed in.
    • Arrays.fill: Fills the entire array, or part thereof, with a given value.
    • Arrays.hashcode: is 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, which allows a variable to be passed to   quickly, and the Arrays.hashcode Method--simply passing in a value, not an 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 a method if you want to copy the entire array or part of it to another array System.arraycopy . 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 T[] Collection.toArray( T[] a ) copied to the array using this method. It is usually called in this way:

1 returncoll.toArray( newT[ coll.size() ] );

This method allocates a large enough array to store all the collections so that toArray no more space is allocated 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. PriorityQueuealso added in Java 1.5. The last version of the non-thread-safe collection schema is ArrayDeque 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, it is ArrayList possible to 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 ArrayList based on the principle of implementation--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 can be used ListIterators . If you want to use an Queue/Deque implementation (you just have to read the first and last element on the line)--consider ArrayDeque replacing it.
    • Vector: A version with the thread synchronization method ArrayList . Now it's in ArrayList the right place.
Queues/deques
    • Arraydeque: Deque is based on arrays (ring buffers) with end-to-end pointers. and LinkedList different, this class does not implement an List interface. Therefore, you cannot remove any elements without the end-to-end elements. This analogy is 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 something Else Deque instead ( ArrayDeque better).
    • Priorityqueue: A priority-based queue. Use the natural order or the set of comparators to sort. His main attribute-- poll/peek/remove/element returns the minimum value of a queue. Not only that, the PriorityQueue interface is implemented Iterable , and the queue is iterated without sorting (or other order). In a collection that needs to be sorted, it is easier to use this queue than TreeSet waiting for other queues.
Maps
  • HASHMAP: The most common Map implementation. It just corresponds to a key and a value, and there is no other function. For complex hashCode method methods, get/put there is a fixed degree of complexity.
  • ENUMMAP: Enumeration type as the key value Map . 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 old HashMap synchronous version, also used in the new code HashMap .
  • Identityhashmap: This is a special Map version that violates the general Map rule: it uses "= =" to compare references instead of calls Object.equals to determine equality. This feature makes this collection very useful in the algorithm that traverses the chart-it is easy to IdentityHashMap store processed nodes and related data in.
  • Linkedhashmap: HashMap and LinkedList The union of all elements is stored in the order of insertion LinkedList . This is why iterations LinkedHashMap of entries (entry), keys, and values always follow 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 requires implementation equals methods and Comparable/Comparator . compareToneed consistency. This class implements an interface that can have a NavigableMap different entry than the number of keys, can get the previous or next entry of the key, and can get another key of a Map certain range (roughly the same as the SQL BETWEEN operator), and some other methods.
  • Weakhashmap: This Map is usually used in the data cache. It stores the key in WeakReference , that is, 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 a weak reference m.put(key, new WeakReference(value)) .
Sets
    • HashSet: An implementation based on HashMap Set . Where all values are "false values" ( Object the same object has HashMap the same performance.) Based on this feature, this data structure consumes more unnecessary memory.
    • Enumset: The value is of type enum Set . Each of the Java enum maps is mapped into a different one int . This allows the use BitSet of a similar set structure, where each bit is mapped to a different one enum . EnumSetThere are two implementations,--by RegularEnumSet a single long store (able to store 64 enumerated values, 99.9% of cases is sufficient),-- JumboEnumSet by long[] storage.
    • BitSet: a bit set. It is often necessary to consider BitSet processing a set of dense integers Set (such as a collection of IDs starting with a pre-known number). This class is used long[] to store bit .
    • Linkedhashmap: HashSet As with, this class is based on LinkedHashMap implementation. This is the only one that keeps the insertion order Set .
    • TreeSet: With HashSet similar. This class is based on an TreeMap instance. This is the only one sorted in the Single threaded section Set .
Java.util.Collections

It's like having a special handle to the java.util.Arrays array, which is also handled in Java for the collection java.util.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 an 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: Get the thread-safe version of the collection (multithreaded operations are inexpensive but inefficient, and do not support similar put or update such compound operations)
    • 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: And string.indexof (String)/LastIndexOf (String) The method is similar-find 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 comparer when sorting the list.
    • collections.rotate: Rotates the element based on a given distance.
    • collections.shuffle: Randomly emit 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 locations of the two elements in the collection (most developers do it themselves).
Concurrent Collections

This section describes the java.util.concurrent collection of thread-safe threads in the package. The primary properties of these collections are an indivisible method that must be performed. Because concurrent operations, such as add or update check , again update , have more than one call, they 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 / ConcurrentSkipListSetand LinkedBlockingDeque is newly added in Java 1.6. Java 1.7 joins the final ConcurrentLinkedDeque andLinkedTransferQueue

Lists
    • Copyonwritearraylist:list implementations each update produces a new, implicitly-array copy, so this is a costly operation. A collection, such as a collection, that is typically used in a traversal operation that is more than an update operation listeners/observers .
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, adding elements will not clog. 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: Delayed The collection of unbounded save elements. 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 ScheduledThreadPoolExecutor ).
    • Linkedblockingdeque/linkedblockingqueue: Optionally bounded or unbounded based on the implementation of a linked list. Used in cases where the queue is empty or full ReentrantLock-s .
    • 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.
    • Priorityblockingqueue: PriorityQueue the unbounded version.
    • 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 interface is not needed Queue , the Exchanger function of the response can also be done through the class.
Maps
    • Concurrenthashmap: get operation full concurrent access, put operation can configure a hash table for concurrent operations. The level of concurrency can be set through the constructor concurrencyLevel parameter (default Level 16). This parameter Map divides some partitions internally. Only the put updated partition is locked during operation. This Map is not HashMap a substitute thread-safe version-any get-then-put operations need to be synchronized externally.
    • Concurrentskiplistmap: Based on the implementation of the Jump List (skip list) ConcurrentNavigableMap . Essentially, this collection can be TreeMap used as a thread-safe version.
Sets
    • Concurrentskiplistset: Used ConcurrentSkipListMap to store thread-safe Set .
    • Copyonwritearrayset: Used CopyOnWriteArrayList to store thread-safe Set .
Related reading
    • Java Basic Type Collection library: Trove:trove Library Overview-a collection library that stores Java basic type data (unlike the classes in most JDK Objects ).
    • Java common data type memory consumption (1): The memory footprint of various classes is called, including enums, Enummap, Enumset, BitSet, ArrayList, LinkedList, and Arraydeque.
    • Java Common data type memory footprint (2): HashMap, HashSet, Linkedhashmap, Linkedhashset, TreeMap, TreeSet, and JDK 7 priorityqueue memory footprint, and the corresponding trove substitution class description.
Recommended Reading

If you want to learn more about the Java collection, we recommend reading the following books:

    • Cay S. Horstmann. Core Java Volume i–fundamentals (9th Edition) (Core Series): The 13th chapter describes the Java collection.
    • Naftalin, Wadler. Java Generics and collections: The 2nd part of the book (chapters 10th through 17th) specifically discusses the Java collection.
    • Goetz, Peierls, Bloch, Bowbeer, Holmes, Lea. Java Concurrency in practice: The best Java Concurrency Books. The 5th chapter discusses the concurrency collections introduced in Java 1.5.
Summarize

Single Thread Concurrent
Lists
  • ArrayList --based on generic array
  • linkedlist --deprecated
  • Vector -deprecated (deprecated)
  • copyonwritearraylist --rarely updated, often used to traverse
queues/deques
  • arraydeque --based on generic array
  • Stack -deprecated (DEP recated)
  • priorityqueue -the contents of the read operation are sorted
  • arrayblockingqueue --blocked queues with boundaries
  • concurrentlinkeddeque/concurrentlinkedqueue --Borderless list queue (CAS)
  • Code>delayqueue --element with deferred queue
  • linkedblockingdeque/linkedblockingqueue --linked list queue (with lock), Can be set with bounds
  • linkedtransferqueue --the element ' transfer ' can be w/o stored
  • priorityblockingqueue --concurrency priorityqueue
  • synchronousqueue --Using the Queue interface for Exchanger
Maps
  • HashMap--General Map
  • EnumMap--Key useenum
  • Hashtable--Obsolete (deprecated)
  • IdentityHashMap--use == the key to compare
  • LinkedHashMap--Keep the insertion order
  • TreeMap--Key is sorted
  • WeakHashMap--For caching (cache)
  • ConcurrentHashMap--General concurrency Map
  • ConcurrentSkipListMap--Sorted concurrency map
Sets
  • HashSet--Universal Set
  • EnumSet-- enum Set
  • BitSet--bit or dense integer set
  • LinkedHashSet--Keep the insertion order
  • TreeSet--Sort Set

Java Collection Overview

Related Article

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.