Java collections framework

From HandWiki
Short description: Collections in Java
java.util.Collection class and interface hierarchy
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 also grow and shrink in size automatically when objects are added or removed. Collections cannot hold primitive data types such as int, long, or double.[2] Instead, Collections can hold wrapper classes such as Template:Javadoc, Template:Javadoc, or Template:Javadoc.[3]

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.[4] 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.Cite error: Closing </ref> missing for <ref> tag and ObjectSpace Generic Collection Library (JGL),[5] whose main goal was consistency with the C++ Standard Template Library (STL).Cite error: Closing </ref> missing for <ref> tag 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 states the add(E e) and remove(E e) methods for adding to and removing from a Collection respectively. Also required is the toArray() method, which converts the Collection into an array of Object in the Collection with return type of Object[].[6] Finally, the Template:Javadoc method checks if a specified element is 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 have an Template:Javadoc that goes through all of the elements in the Collection. Additionally, Collection is generic. Any Collection can be written to store any class. For example, Collection<String> can hold strings, and the elements from the Collection can be used as strings without any casting required.[7] Note that the angled brackets < > can hold a type argument that specifies which type the Collection holds.[8]

Three types of collection

There are three generic types of Collection: ordered lists, dictionaries/maps, and sets.

Ordered lists allows 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 ordered lists are called List and 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.

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

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. Two examples for concrete classes that implement List are:

  • Template:Javadoc, which 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.
  • Template:Javadoc. This 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.[9]

Stack class

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. It extends class java.util.Vector with five 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.

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. LinkedList, of course, also implements the List interface and can also be used as one. But it also has the Queue methods. ArrayDeque implements the Queue as an array. Both LinkedList and ArrayDeque also implement the Template:Javadoc interface, giving it more flexibility.[10]

The Template:Javadoc interface extends Queue, and can be used more flexibly. BlockingQueue works like a regular Queue, but additions to and removals from the BlockingQueue are blocking.[11] 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.[12][13]

The java.util.PriorityQueue class implements java.util.Queue, but also alters it.[14] PriorityQueue has an additional Template:Javadoc method.[14] 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.[15]

Double-ended queue (Deque) interfaces

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

The java.util.concurrent.BlockingDeque interface works similarly to java.util.concurrent.BlockingQueue. The same methods for insertion and removal with time limits for waiting for the insertion or removal to become possible are provided. 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.[17]

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. HashSet uses a hash table. More specifically, it uses a Template:Javadoc to store the hashes and elements and to prevent duplicates. java.util.LinkedHashSet extends this 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. 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.[18]

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.[19]

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.[20]

Map interfaces

Maps are defined by the Template:Javadoc interface in Java. Maps are simple 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. Maps are implemented by java.util.HashMap, Template:Javadoc , and Template:Javadoc. HashMap uses a hash table. The hashes of the keys are used to find the elements in various buckets.

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

TreeMap, in contrast to HashMap and LinkedHashMap, 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.[22]

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.[23]

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.[24]

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.[25]

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

See also

Citation

  1. "Lesson: Introduction to Collections". Oracle Corporation. http://download.oracle.com/javase/tutorial/collections/intro/index.html. 
  2. Bloch 2018, pp. 126-129, Chapter §5 Item 28: Prefer lists to arrays.
  3. 3.0 3.1 Horstmann, Cay (2014). Big Java Early Objects. 
  4. "Java Collections Framework". IBM. http://www.digilife.be/quickreferences/PT/Java%20Collections%20Framework.pdf. 
  5. "Generic Collection Library for Java™". http://www.stanford.edu/group/coursework/docsTech/jgl/. 
  6. Bloch 2018, pp. 87-92, Chapter §8 Item 8: Favor composition over inheritance.
  7. "Iterable (Java Platform SE 7 )". Docs.oracle.com. 2013-06-06. http://docs.oracle.com/javase/7/docs/api/java/lang/Iterable.html. 
  8. Bloch 2018, pp. 117-122, Chapter §5 Item 26: Don't use raw types.
  9. "List (Java Platform SE 7 )". Docs.oracle.com. 2013-06-06. http://docs.oracle.com/javase/7/docs/api/java/util/List.html. 
  10. "Queue (Java Platform SE 7)". Docs.oracle.com. 2013-06-06. http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html. 
  11. Bloch 2018, pp. 325-329, Chapter §11 Item 78: Synchronize access to shared mutable data.
  12. "BlockingQueue (Java Platform SE 7)". Docs.oracle.com. 2013-06-06. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html. 
  13. Bloch 2018, pp. 325-329, Chapter §11 Item 81: Prefer concurrency utilities to wait and notify.
  14. 14.0 14.1 Bloch 2018, pp. 280-281, Chapter §9 Item 64: Refer to objects by their interfaces.
  15. "PriorityQueue (Java Platform SE 7)". Docs.oracle.com. 2013-06-06. http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html. 
  16. "Deque (Java Platform SE 7 )". Docs.oracle.com. 2013-06-06. http://docs.oracle.com/javase/7/docs/api/java/util/Deque.html. 
  17. "BlockingDeque (Java Platform SE 7 )". Docs.oracle.com. 2013-06-06. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingDeque.html. 
  18. "Set (Java Platform SE 7 )". Docs.oracle.com. 2013-06-06. http://docs.oracle.com/javase/7/docs/api/java/util/Set.html. 
  19. "SortedSet (Java Platform SE 7 )". Docs.oracle.com. 2013-06-06. http://docs.oracle.com/javase/7/docs/api/java/util/SortedSet.html. 
  20. "NavigableSet (Java Platform SE 7 )". Docs.oracle.com. 2013-06-06. http://docs.oracle.com/javase/7/docs/api/java/util/NavigableSet.html. 
  21. 21.0 21.1 21.2 Bloch 2018, pp. 199-202, Chapter §44 Favor the use of standard functional interfaces.
  22. "Map (Java Platform SE 7 )". Docs.oracle.com. 2013-06-06. http://docs.oracle.com/javase/7/docs/api/java/util/Map.html. 
  23. "SortedMap (Java Platform SE 7 )". Docs.oracle.com. 2013-06-06. http://docs.oracle.com/javase/7/docs/api/java/util/SortedMap.html. 
  24. "NavigableMap (Java Platform SE 7 )". Docs.oracle.com. 2013-06-06. http://docs.oracle.com/javase/7/docs/api/java/util/NavigableMap.html. 
  25. "Collections - Home". Commons.apache.org. 2013-07-04. http://commons.apache.org/proper/commons-collections/. 

References

  • Bloch, Joshua (2018). "Effective Java: Programming Language Guide" (third ed.). Addison-Wesley. ISBN 978-0134685991. 


      Please be cautious adding more external links.

Wikipedia is not a collection of links and should not be used for advertising.

    Excessive or inappropriate links will be removed.
See Wikipedia:External links and Wikipedia:Spam for details.

If there are already suitable links, propose additions or replacements on the article's talk page.

-->