Java collections framework

From Wikipedia, the free encyclopedia
Revision as of 07:37, 25 June 2025 by imported>Bellowhead678 (instatiate→instantiate - toolforge:typos)
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Template:Short description

File:Java.util.Collection hierarchy.svg
java.util.Collection class and interface hierarchy
File:Java.util.Map hierarchy.svg
Java's java.util.Map class and interface hierarchy

The Java collections framework is a set of classes and interfaces that implement commonly reusable collection data structures.[1]

Although referred to as a framework, it works in a manner of a library. The collections framework provides both interfaces that define various collections and classes that implement them.

Differences from Arrays

Collections and arrays are similar in that they both hold references to objects and they can be managed as a group. However, unlike arrays, Collections do not need to be assigned a certain capacity when instantiated. Collections can grow and shrink in size automatically when objects are added or removed.

Collections cannot hold primitive data types such as int, long, or double.Template:Sfn Instead, Collections can hold wrapper classes such as Template:Javadoc, Template:Javadoc, or Template:Javadoc.[2]

Collections are generic and hence invariant, but arrays are covariant. This can be considered an advantage of generic objects such as Collection when compared to arrays, because under circumstances, using the generic Collection instead of an array prevents run time exceptions by instead throwing a compile-time exception to inform the developer to fix the code. For example, if a developer declares an Object[] object, and assigns the Object[] object to the value returned by a new Long[] instance with a certain capacity, no compile-time exception will be thrown. If the developer attempts to add a String to this Long[] object, the java program will throw an ArrayStoreException. On the other hand, if the developer instead declared a new instance of a Collection<Object> as ArrayList<Long>, the Java compiler will (correctly) throw a compile-time exception to indicate that the code is written with incompatible and incorrect type, thus preventing any potential run-time exceptions.The developer can fix the code by instantianting Collection<Object> as an ArrayList<Object> object. If the code is using Java SE7 or later versions, the developer can instantiate Collection<Object> as an ArrayList<> object by using the diamond operatorTemplate:Sfn

Collections are generic and hence reified, but arrays are not reified.Template:Sfn

History

Collection implementations in pre-JDK 1.2 versions of the Java platform included few data structure classes, but did not contain a collections framework.[3] The standard methods for grouping Java objects were via the array, the Vector, and the Hashtable classes, which unfortunately were not easy to extend, and did not implement a standard member interface.[4]Template:Better source needed

To address the need for reusable collection data structures, several independent frameworks were developed,[3] the most used being Doug Lea's Collections package,[5] and ObjectSpace Generic Collection Library (JGL),[6] whose main goal was consistency with the C++ Standard Template Library (STL).[7]Template:Better source needed

The collections framework was designed and developed primarily by Joshua Bloch, and was introduced in JDK 1.2. It reused many ideas and classes from Doug Lea's Collections package, which was deprecated as a result.[5] Sun Microsystems chose not to use the ideas of JGL, because they wanted a compact framework, and consistency with C++ was not one of their goals.[8]Template:Better source needed

Doug Lea later developed a concurrency package, comprising new Collection-related classes.[9] An updated version of these concurrency utilities was included in JDK 5.0 as of JSR 166.

Architecture

Almost all collections in Java are derived from the java.util.Collection interface. Collection defines the basic parts of all collections.

The interface has the add(E e) and remove(E e) methods for adding to and removing from a Collection respectively. It also has the toArray() method, which converts the Collection into an array of Objects in the Collection (with return type of Object[]).Template:Sfn Finally, the Template:Javadoc method checks if a specified element exists in the Collection.

The Collection interface is a subinterface of Template:Javadoc, so any Collection may be the target of a for-each statement. (The Iterable interface provides the Template:Javadoc method used by for-each statements.) All Collections implement Template:Javadoc to scan all of the elements in the Collection.

Collection is generic. Any Collection can store any Object. For example, any implementation of Collection<String> contains String objects. No casting is required when using the String objects from an implementation of Collection<String>.[10] Note that the angled brackets < > can hold a type argument that specifies which type the Collection holds.Template:Sfn

Types of collection

There are several generic types of Collection: Queues, maps, lists and sets.

Queues allow the programmer to insert items in a certain order and retrieve those items in the same order. An example is a waiting list. The base interfaces for queues are called Queue.

Dictionaries/Maps store references to objects with a lookup key to access the object's values. One example of a key is an identification card. The base interface for dictionaries/maps is called Map.

Lists are finite collections where it can store the same value multiple times.

Sets are unordered collections that can be iterated and contain each element at most once. The base interface for sets is called Set.[2]

List interface

Lists are implemented in the collections framework via the Template:Javadocinterface. It defines a list as essentially a more flexible version of an array. Elements have a specific order, and duplicate elements are allowed. Elements can be placed in a specific position. They can also be searched for within the list.

List implementations

There are several concrete classes that implement List, including Template:Java and all of its corresponding subclasses, as well as Template:Java.

AbstractList class

The direct subclasses of Template:Java class include Template:Java, Template:Java and Template:Java.

Template:Java is an example of a skeletal implementation, which leverages and combines the advantages of interfaces and abstract classes by making it easy for the developer to develop their own implementation for the given interface.Template:Sfn

ARRAYLIST CLASSES

The Template:Javadoc class implements the List as an array. Whenever functions specific to a List are required, the class moves the elements around within the array in order to do it.

LinkedList class

The Template:Javadoc class stores the elements in nodes that each have a pointer to the previous and next nodes in the List. The List can be traversed by following the pointers, and elements can be added or removed simply by changing the pointers around to place the node in its proper place.[11]

Vector class

The Template:Java class has Template:Java as its direct subclass. This is an example of a violation of the composition over inheritance principle in the Java platform libraries, since in computer science, a vector is generally not a stack.Template:Sfn Composition would have been more appropriate in this scenario.Template:Sfn

Stack class

The Stack class extends class java.util.Vector with five operations that allow a Vector to be treated as a Stack. Stacks are created using Template:Javadoc. The Stack offers methods to put a new object on the Stack (method push(E e)) and to get objects from the Stack (method pop()). A Stack returns the object according to last-in-first-out (LIFO), e.g. the object which was placed latest on the Stack is returned first. java.util.Stack is a standard implementation of a stack provided by Java.

The Stack class represents a last-in-first-out (LIFO) stack of objects. The Stack class has five additional operations that allow a Vector to be treated as a Stack. The usual push(E e) and pop() operations are provided, as well as a method (peek()) to peek at the top item on the Stack, a method to test for whether the Stack is empty (empty()), and a method to search the Stack for an item and discover how far it is from the top (search(Object o)). When a Stack is first created, it contains no items.

CopyOnWriteArrayList class

The CopyOnWriteArrayList extends the Object class, and does not extend any other classes. CopyOnWriteArrayList allows for thread-safety without performing excessive synchronization.Template:Sfn

In some scenarios, synchronization is mandatory. For example, if a method modifies a static field, and the method must be called by multiple threads, then synchronization is mandatory and concurrency utilities such as CopyOnWriteArrayList should not be used.Template:Sfn

However synchronization can incur a performance overhead. For scenarios where synchronization is not mandatory, then the CopyOnWriteArrayList is a viable, thread-safe alternative to synchronization that leverages multi-core processors and results in higher CPU utilization. Template:Sfn

Queue interfaces

The Template:Javadoc interface defines the queue data structure, which stores elements in the order in which they are inserted. New additions go to the end of the line, and elements are removed from the front. It creates a first-in first-out system. This interface is implemented by java.util.LinkedList, Template:Javadoc, and Template:Javadoc.

Queue implementations

AbstractQueue class

The direct subclasses of Template:Java class include Template:Java, Template:Java, Template:Java, Template:Java, Template:Java. Template:Java and Template:Java.

Note that Template:Java and Template:Java both extend Template:Java but do not extend any other abstract classes such as Template:Java.

Template:Java is an example of a skeletal implementation.

PriorityQueue class

The java.util.PriorityQueue class implements java.util.Queue, but also alters it.Template:Sfn PriorityQueue has an additional Template:Javadoc method.Template:Sfn Instead of elements being ordered in the order in which they are inserted, they are ordered by priority. The method used to determine priority is either the Template:Javadoc method in the elements, or a method given in the constructor. The class creates this by using a heap to keep the items sorted.[12]

ConcurrentLinkedQueue class

The java.util.concurrent.ConcurrentLinkedQueue class extends Template:Java. ConcurrentLinkedQueue implements the Template:Java interface.Template:Sfn

The ConcurrentLinkedQueue class is a thread-safe collection, since for any an element placed inside a Template:Java, the Java Collection Library guarantees that the element is safely published by allowing any thread to get the element from the collection.Template:Sfn An object is said to be safely published if the object's state is made visible to all other thread at the same point in time.Template:Sfn Safe publication usually requires synchronization of the publishing and consuming threads.Template:Sfn

BlockingQueue interface

The Template:Javadoc interface extends Queue.Template:Sfn

The Template:Java interface has the following direct sub-interfaces: Template:Java and Template:Java. Template:Java works like a regular Queue, but additions to and removals from the BlockingQueue are blocking.Template:Sfn If Template:Javadoc is called on an empty BlockingQueue, it can be set to wait either a specified time or indefinitely for an item to appear in the BlockingQueue. Similarly, adding an item using the method Template:Javadoc is subject to an optional capacity restriction on the BlockingQueue, and the method can wait for space to become available in the BlockingQueue before returning. BlockingQueue interface introduces a method Template:Javadoc which removes and gets the head of the BlockingQueue, and waits until the BlockingQueue is no longer empty if required.[13]Template:Sfn

Double-ended queue (Deque) interfaces

The Template:Java interface extends the Template:Java interface.Template:Sfn Template:Java creates a double-ended queue. While a regular Template:Java only allows insertions at the rear and removals at the front, the Template:Java allows insertions or removals to take place both at the front and the back. A Template:Java is like a Template:Java that can be used forwards or backwards, or both at once. Additionally, both a forwards and a backwards iterator can be generated. The Template:Java interface is implemented by java.util.ArrayDeque and java.util.LinkedList.[14]

Deque implementations

LinkedList class

LinkedList, of course, also implements the List interface and can also be used as one. But it also has the Queue methods. LinkedList implements the Template:Javadoc interface, giving it more flexibility.[15]

ArrayDeque class

ArrayDeque implements the Queue as an array. Similar to LinkedList, ArrayDeque also implements the Template:Javadoc interface.[15]

BlockingDeque interface

The java.util.concurrent.BlockingDeque interface extends java.util.concurrent.BlockingQueue.Template:Sfn Template:Java is similar to Template:Java. It provides the same methods for insertion and removal with time limits for waiting for the insertion or removal to become possible. However, the interface also provides the flexibility of a Deque. Insertions and removals can take place at both ends. The blocking function is combined with the Deque function.[16]

Set interfaces

Java's Template:Javadocinterface defines the Set. A Set can't have any duplicate elements in it. Additionally, the Set has no set order. As such, elements can't be found by index. Set is implemented by Template:Javadoc, Template:Javadoc, and Template:Javadoc.

Set interface implementations

There are several implementations of the Set interface, including Template:Java and its subclasses, and the final static inner class Template:Java (where Template:Java and Template:Java are formal type parameters).

AbstractSet

Template:Java is a skeletal implementation for the Template:Java interface.Template:Sfn

Direct subclasses of Template:Java include Template:Java, Template:Java, Template:Java, Template:Java and Template:Java.

EnumSet class

The Template:Java class extends Template:Java. The Template:Java class has no public constructors, and only contain static factory methods.Template:Sfn

Template:Java contains the static factory method Template:Java.Template:Sfn This method is an aggregation method.Template:Sfn It takes in several parameters, takes into account of the type of the parameters, then returns an instance with the appropriate type.Template:Sfn As of 2018, In Java SE8 OpenJDK implementation uses two implementations of Template:Java which are invisible to the client, which are Template:Java and Template:Java.Template:Sfn If the Template:Java no longer provided any performance benefits for small enum types, it could be removed from the library without negatively impacting the Java Collection Library.Template:Sfn

Template:Java is a good replacement for the bit fields, which is a type of set, as described below.Template:Sfn

Traditionally, whenever developers encountered elements of an enumerated type that needs to be placed in a set, the developer would use the int enum pattern in which every constant is assigned a different power of 2.Template:Sfn This bit representation enables the developer to use the bitwise OR operation, so that the constants can be combined into a set, also known as a bit field. This bit field representation enables the developer to make efficient set-based operations and bitwise arithmetic such as intersection and unions.Template:Sfn

However, there are many problems with bit field representation approach. A bit field is less readable than an int enum constant.Template:Sfn Also, if the elements are represented by bit fields, it is impossible to iterate through all of these elements.Template:Sfn

A recommended alternative approach is to use an Template:Java, where an int enum is used instead of a bit field.Template:Sfn This approach uses an Template:Java to represent the set of values that belong to the same Template:Java type.Template:Sfn Since the Template:Java implements the Template:Java interface and no longer requires the use of bit-wise operations, this approach is more type-safe.Template:Sfn Furthermore, there are many static factories that allow for object instantiation, such as the method Template:Java method.Template:Sfn

After the introduction of the Template:Java, the bit field representation approach is considered to be obsolete.Template:Sfn

HashSet class

HashSet uses a hash table. More specifically, it uses a Template:Javadoc to store the hashes and elements and to prevent duplicates.

LinkedHashSet class

The java.util.LinkedHashSet class extends Template:Java by creating a doubly linked list that links all of the elements by their insertion order. This ensures that the iteration order over the Set is predictable.

CopyOnWriteArraySet class

CopyOnWriteArraySet is a concurrent replacement for a synchronized Template:Java. It provides improved concurrency in many situations by removing the need to perform synchronization or making a copy of the object during iteration, similar to how CopyOnWriteArrayList acts as the concurrent replacement for a synchronized Template:Java.Template:Sfn On the other hand, similar to CopyOnWriteArrayList, CopyOnWriteArraySet should not be used when synchronization is mandatory.

SortedSet interface

The java.util.SortedSet interface extends the java.util.Set interface. Unlike a regular Set, the elements in a SortedSet are sorted, either by the element's compareTo(T o) method, or a method provided to the constructor of the SortedSet. The first and last elements of the SortedSet can be retrieved using the first() and last() methods respectively, and subsets can be created via minimum and maximum values, as well as beginning or ending at the beginning or ending of the SortedSet. The java.util.TreeSet class implements the SortedSet interface.[17]

NavigableSet interface

The Template:Javadoc interface extends the java.util.SortedSet interface and has a few additional methods. The floor(E e), ceiling(E e), lower(E e), and higher(E e) methods find an element in the set that's close to the parameter. Additionally, a descending iterator over the items in the Set is provided. As with SortedSet, java.util.TreeSet implements NavigableSet.[18]

TreeSet class

java.util.TreeSet uses a red–black tree implemented by a Template:Javadoc. The red–black tree ensures that there are no duplicates. Additionally, it allows TreeSet to implement Template:Javadoc.[19]

ConcurrentSkipListSet class

ConcurrentSkipListSet acts as a concurrent replacement for implementations of a synchronized Template:Java. For example it replaces a Template:Java that has been wrapped by the Template:Java method. Template:Sfn

Map interfaces

Maps are defined by the Template:Javadoc interface in Java.

Map interface implementations

Maps are data structures that associate a key with an element. This lets the map be very flexible. If the key is the hash code of the element, the Map is essentially a Set. If it's just an increasing number, it becomes a list.

Examples of Template:Java implementations include Template:Javadoc, Template:Javadoc , and Template:Javadoc.

AbstractMap class

Template:Java is an example of a skeletal implementation.Template:Sfn

The direct subclasses of Template:Java class include Template:Java, Template:Java, Template:Java, Template:Java, Template:Java and Template:Java.

EnumMap

Template:Java extends Template:Java. Template:Java has comparable speed with an ordinal-indexed array.Template:Sfn This is because Template:Java internally uses an array, with implementation details completely hidden from the developer.Template:Sfn Hence, the EnumMap gets the type safety of a Template:Java while the performance advantages of an array.Template:Sfn

HashMap

Template:Java uses a hash table. The hashes of the keys are used to find the elements in various buckets. The Template:Java is a hash-based collection. Template:Sfn

LinkedHashMap

Template:Java extends Template:Java by creating a doubly linked list between the elements, allowing them to be accessed in the order in which they were inserted into the map. Template:Java contains a protected removeEldestEntry method which is called by the put method whenever a new key is added to the Map.Template:Sfn The Map removes its eldest entry whenever removeEldestEntry returns true.Template:Sfn The removeEldestEntry method can be overridden.Template:Sfn

TreeMap

Template:Java, in contrast to Template:Java and Template:Java, uses a red–black tree. The keys are used as the values for the nodes in the tree, and the nodes point to the elements in the Map.[20]

ConcurrentHashMap

Template:Java is similar to Template:Java and is also a hash-based collection. Template:Sfn However, there are a number of differences, such as the differences in the locking strategy they use.

The Template:Java uses a completely different locking strategy to provide improved scalability and concurrency.Template:Sfn Template:Java does not synchronize every method using the same lock.Template:Sfn Instead, Template:Java use a mechanism known as lock striping.Template:Sfn This mechanism provides a finer-grained locking mechanism.Template:Sfn It also permits a higher degree of shared access.Template:Sfn

ConcurrentSkipListMap class

ConcurrentSkipListMap acts as a concurrent replacement for implementations of a synchronized Template:Java. ConcurrentSkipListMap is very similar to ConcurrentSkipListSet, since ConcurrentSkipListMap replaces a Template:Java that has been wrapped by the Template:Java method.Template:Sfn

Map subinterfaces

SortedMap interface

The Template:Javadoc interface extends the java.util.Map interface. This interface defines a Map that's sorted by the keys provided. Using, once again, the compareTo() method or a method provided in the constructor to the SortedMap, the key-element pairs are sorted by the keys. The first and last keys in the Map can be called by using the firstKey() and lastKey() methods respectively. Additionally, submaps can be created from minimum and maximum keys by using the subMap(K fromKey, K toKey) method. SortedMap is implemented by java.util.TreeMap.[21]

NavigableMap interface

The Template:Javadoc interface extends java.util.SortedMap in various ways. Methods can be called that find the key or map entry that's closest to the given key in either direction. The map can also be reversed, and an iterator in reverse order can be generated from it. It's implemented by java.util.TreeMap.[22]

ConcurrentMap interface

Template:Main article The Template:Javadoc interface extends the java.util.Map interface. This interface a thread Safe Template:Java interface, introduced as of Java programming language's Java Collections Framework version 1.5.Template:Sfn

Extensions to the Java collections framework

Java collections framework is extended by the Apache Commons Collections library, which adds collection types such as a bag and bidirectional map, as well as utilities for creating unions and intersections.[23]

Google has released its own collections libraries as part of the guava libraries.

See also

Script error: No such module "Portal".

Citation

Template:Reflist

References

  • Script error: No such module "citation/CS1".
  • Script error: No such module "citation/CS1".

Template:Sister project Template:Java (Sun)

Template:Prone to spam

  1. Script error: No such module "citation/CS1".
  2. a b Script error: No such module "citation/CS1".
  3. a b Script error: No such module "citation/CS1".
  4. Script error: No such module "citation/CS1".
  5. a b Script error: No such module "citation/CS1".
  6. Script error: No such module "citation/CS1".
  7. Script error: No such module "citation/CS1".
  8. Script error: No such module "citation/CS1".
  9. Script error: No such module "citation/CS1".
  10. Script error: No such module "citation/CS1".
  11. Script error: No such module "citation/CS1".
  12. Script error: No such module "citation/CS1".
  13. Script error: No such module "citation/CS1".
  14. Script error: No such module "citation/CS1".
  15. a b Script error: No such module "citation/CS1".
  16. Script error: No such module "citation/CS1".
  17. Script error: No such module "citation/CS1".
  18. Script error: No such module "citation/CS1".
  19. Script error: No such module "citation/CS1".
  20. Script error: No such module "citation/CS1".
  21. Script error: No such module "citation/CS1".
  22. Script error: No such module "citation/CS1".
  23. Script error: No such module "citation/CS1".