The Java collections framework is a set of classes and interfaces that implement commonly reusable collection data structures .
45-956: 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. Collection s and arrays are similar in that they both hold references to objects and they can be managed as a group. However, unlike arrays, Collection s do not need to be assigned a certain capacity when instantiated. Collection s can grow and shrink in size automatically when objects are added or removed. Collection s cannot hold primitive data types such as int , long , or double . Instead, Collection s can hold wrapper classes such as java.lang.Integer , java.lang.Long , or java.lang.Double . Collection s 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
90-583: A ConcurrentLinkedQueue , the Java Collection Library guarantees that the element is safely published by allowing any thread to get the element from the collection. 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. Safe publication usually requires synchronization of the publishing and consuming threads. The java.util.concurrent.BlockingQueue interface extends Queue . The BlockingQueue interface has
135-491: 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
180-515: 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. The CopyOnWriteArrayList extends
225-588: A concrete software system with a software framework, developers utilize the hot spots according to the specific needs and requirements of the system. Software frameworks rely on the Hollywood Principle : "Don't call us, we'll call you." This means that the user-defined classes (for example, new subclasses) receive messages from the predefined framework classes. Developers usually handle this by implementing superclass abstract methods . Foreach loop Too Many Requests If you report this error to
270-506: A framework consists of composing and subclassing the existing classes. The necessary functionality can be implemented by using the Template Method Pattern in which the frozen spots are known as invariant methods and the hot spots are known as variant or hook methods. The invariant methods in the superclass provide default behaviour while the hook methods in each subclass provide custom behaviour. When developing
315-473: 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. The java.util.Queue interface defines the queue data structure, which stores elements in the order in which they are inserted. New additions go to
360-464: A product. Further, due to the complexity of their APIs, the intended reduction in overall development time may not be achieved due to the need to spend additional time learning to use the framework; this criticism is clearly valid when a special or new framework is first encountered by development staff. If such a framework is not used in subsequent job taskings, the time invested in learning the framework can cost more than purpose-written code familiar to
405-512: A result. 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. Doug Lea later developed a concurrency package , comprising new Collection-related classes. An updated version of these concurrency utilities was included in JDK 5.0 as of JSR 166 . Almost all collections in Java are derived from the java.util.Collection interface. Collection defines
450-422: A standard way to build and deploy applications and is a universal, reusable software environment that provides particular functionality as part of a larger software platform to facilitate the development of software applications , products and solutions. Software frameworks may include support programs, compilers, code libraries, toolsets, and application programming interfaces (APIs) that bring together all
495-450: A working system, thereby reducing overall development time. For example, a team using a web framework to develop a banking website can focus on writing code particular to banking rather than the mechanics of request handling and state management . Frameworks often add to the size of programs, a phenomenon termed " code bloat ". Due to customer-demand-driven applications needs, both competing and complementary frameworks sometimes end up in
SECTION 10
#1732790977021540-522: 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. The java.util.ArrayList 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. The java.util.LinkedList class stores
585-407: Is an example of a skeletal implementation . The java.util.PriorityQueue class implements java.util.Queue , but also alters it. PriorityQueue has an additional comparator() method. 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 java.lang.Comparable#compareTo(T) method in
630-651: Is called Set . Lists are implemented in the collections framework via the java.util.List interface. 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. There are several concrete classes that implement List , including AbstractList and all of its corresponding subclasses, as well as CopyOnWriteArrayList . The direct subclasses of AbstractList class include AbstractSequentialList , ArrayList and Vector . AbstractList
675-609: Is combined with the Deque function. Java's java.util.Set interface 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 java.util.HashSet , java.util.LinkedHashSet , and java.util.TreeSet . There are several implementations of the Set interface, including AbstractSet and its subclasses, and
720-463: Is implemented by java.util.ArrayDeque and java.util.LinkedList . 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 java.util.Deque interface, giving it more flexibility. ArrayDeque implements the Queue as an array. Similar to LinkedList , ArrayDeque also implements
765-512: Is required when using the String objects from an implementation of Collection<String> . Note that the angled brackets < > can hold a type argument that specifies which type the Collection holds. 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
810-430: Is user-defined). For those frameworks that generate code, for example, "elegance" would imply the creation of code that is clean and comprehensible to a reasonably knowledgeable programmer (and which is therefore readily modifiable), versus one that merely generates correct code. The elegance issue is why relatively few software frameworks have stood the test of time: the best frameworks have been able to evolve gracefully as
855-475: The java.util.Deque interface. The java.util.concurrent.BlockingDeque interface extends java.util.concurrent.BlockingQueue . BlockingDeque is similar to BlockingQueue . 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
900-556: The Collection . The Collection interface is a subinterface of java.lang.Iterable , so any Collection may be the target of a for-each statement. (The Iterable interface provides the iterator() method used by for-each statements.) All Collection s have an java.util.Iterator that goes through 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
945-509: The Object class, and does not extend any other classes. CopyOnWriteArrayList allows for thread-safety without performing excessive synchronization. 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. However synchronization can incur
SECTION 20
#1732790977021990-435: The Queue interface. 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
1035-521: The RegularEnumSet no longer provided any performance benefits for small enum types, it could be removed from the library without negatively impacting the Java Collection Library. Software framework In computer programming , a software framework is an abstraction in which software , providing generic functionality, can be selectively changed by additional user-written code, thus providing application-specific software. It provides
1080-460: 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
1125-525: The Java platform included few data structure classes, but did not contain a collections framework. 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. To address the need for reusable collection data structures , several independent frameworks were developed,
1170-399: The Java platform libraries, since in computer science , a vector is generally not a stack . Composition would have been more appropriate in this scenario. 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 java.util.Stack . The Stack offers methods to put a new object on
1215-409: 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 Object s in the Collection (with return type of Object[] ). Finally, the contains(E e) method checks if a specified element exists in
1260-412: The code by instantianting Collection<Object> as an ArrayList<Object> object. If the code is using Java SE7 or later versions, the developer can instatiate Collection<Object> as an ArrayList<> object by using the diamond operator Collection s are generic and hence reified , but arrays are not reified. Collection implementations in pre- JDK 1.2 versions of
1305-414: The common code of the enterprise, instead of using a generic "one-size-fits-all" framework developed by third parties for general purposes. An example of that would be how the user interface in such an application package as an office suite grows to have common look, feel, and data-sharing attributes and methods, as the once disparate bundled applications, grow unified into a suite that is tighter and smaller;
1350-411: The different components to enable development of a project or system . Frameworks have key distinguishing features that separate them from normal libraries : The designers of software frameworks aim to facilitate software developments by allowing designers and programmers to devote their time to meeting software requirements rather than dealing with the more standard low-level details of providing
1395-414: 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. The Vector class has Stack as its direct subclass. This is an example of a violation of the composition over inheritance principle in
Java collections framework - Misplaced Pages Continue
1440-408: The elements, or a method given in the constructor. The class creates this by using a heap to keep the items sorted. The java.util.concurrent.ConcurrentLinkedQueue class extends java . util . AbstractQueue . ConcurrentLinkedQueue implements the java . util . Queue interface. The ConcurrentLinkedQueue class is a thread-safe collection, since for any an element placed inside
1485-654: 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 , java.util.ArrayDeque , and java.util.PriorityQueue . The direct subclasses of AbstractQueue class include ArrayBlockingQueue , ConcurrentLinkedQueue , DelayeQueue , LinkedBlockingDeque , LinkedBlockingQueue . LinkedTransferQueue and PriorityBlockingQueue . Note that ArrayDeque and ConcurrentLinkedDeque both extend AbstractCollection but do not extend any other abstract classes such as AbstractQueue . AbstractQueue
1530-534: The final static inner class ConcurrentHashMap . KeySetView < K , V > (where K and V are formal type parameters). AbstractSet is a skeletal implementation for the Set interface. Direct subclasses of AbstractSet include ConcurrentSkipListSet , CopyOnWriteArraySet , EnumSet , HashSet and TreeSet . The EnumSet class extends AbstractSet . The EnumSet class has no public constructors, and only contain static factory methods. EnumSet contains
1575-470: The following direct sub-interfaces: BlockingDeque and TransferQueue . BlockingQueue works like a regular Queue , but additions to and removals from the BlockingQueue are blocking. If remove(Object o) 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
1620-459: 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
1665-424: The method add(Object o) 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 take() which removes and gets the head of the BlockingQueue , and waits until the BlockingQueue is no longer empty if required. The Deque interface extends
1710-487: The most used being Doug Lea 's Collections package , and ObjectSpace Generic Collection Library (JGL), whose main goal was consistency with the C++ Standard Template Library (STL). 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
1755-417: The newer/evolved suite can be a product that shares integral utility libraries and user interfaces. This trend in the controversy brings up an important issue about frameworks. Creating a framework that is elegant, versus one that merely solves a problem, is still rather a craft than a science. "Software elegance " implies clarity, conciseness, and little waste (extra or extraneous functionality, much of which
1800-434: The output product, nor its relative efficiency and conciseness. Using any library solution necessarily pulls in extras and unused extraneous assets unless the software is a compiler-object linker making a tight (small, wholly controlled, and specified) executable module. The issue continues, but a decade-plus of industry experience has shown that the most effective frameworks turn out to be those that evolve from re-factoring
1845-476: The overall architecture of a software system, that is to say its basic components and the relationships between them. These remain unchanged (frozen) in any instantiation of the application framework. Hot spots represent those parts where the programmers using the framework add their own code to add the functionality specific to their own project. In an object-oriented environment, a framework consists of abstract and concrete classes . Instantiation of such
Java collections framework - Misplaced Pages Continue
1890-404: The project's staff; many programmers keep copies of useful boilerplate code for common needs. However, once a framework is learned, future projects can be faster and easier to complete; the concept of a framework is to make a one-size-fits-all solution set, and with familiarity, code production should logically rise. There are no such claims made about the size of the code eventually bundled with
1935-505: 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
1980-401: The static factory method EnumSet . of () . This method is an aggregation method. It takes in several parameters, takes into account of the type of the parameters, then returns an instance with the appropriate type. As of 2018, In Java SE8 OpenJDK implementation uses two implementations of EnumSet which are invisible to the client, which are RegularEnumSet and JumboEnumSet . If
2025-546: The underlying technology on which they were built advanced. Even there, having evolved, many such packages will retain legacy capabilities bloating the final software as otherwise replaced methods have been retained in parallel with the newer methods. Software frameworks typically contain considerable housekeeping and utility code in order to help bootstrap user applications, but generally focus on specific problem domains, such as: According to Pree, software frameworks consist of frozen spots and hot spots . Frozen spots define
#20979