Misplaced Pages

Java collections framework

Article snapshot taken from Wikipedia with creative commons attribution-sharealike license. Give it a read and then ask your questions in the chat. We can research this topic together.

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

#372627

59-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

118-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

177-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

236-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

295-505: A C-style for loop with an array index: Collections in Groovy can also be iterated over using the each keyword and a closure. By default, the loop dummy is named it Haskell allows looping over lists with monadic actions using mapM_ and forM_ ( mapM_ with its arguments flipped) from Control.Monad : It's also possible to generalize those functions to work on applicative functors rather than monads and any data structure that

354-604: 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 In computer programming , foreach loop (or for-each loop )

413-410: A foreach construct. However, it has several standard data structures that can be used as collections, and foreach can be made easily with a macro . However, two obvious problems occur: C string as a collection of char C int array as a collection of int (array size known at compile-time) Most general: string or array as collection (collection size known at run-time) In C# , assuming that myArray

472-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

531-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

590-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

649-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

SECTION 10

#1732782406373

708-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

767-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

826-399: Is syntactic sugar equivalent to: The compiler uses argument-dependent lookup to resolve the begin and end functions. The C++ Standard Library also supports for_each , that applies each element to a function, which can be any predefined function or a lambda expression. While range-based for is only from the start to the end, the range or direction can be changed by altering

885-484: Is a control flow statement for traversing items in a collection . foreach is usually used in place of a standard for loop statement . Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages, an iterator , even if implicit,

944-493: Is an array of integers: Language Integrated Query (LINQ) provides the following syntax, accepting a delegate or lambda expression : C++11 provides a foreach loop. The syntax is similar to that of Java : C++11 range-based for statements have been implemented in GNU Compiler Collection (GCC) (since version 4.6), Clang (since version 3.0) and Visual C++ 2012 (version 11 ) The range-based for

1003-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

1062-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

1121-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

1180-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

1239-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

SECTION 20

#1732782406373

1298-437: Is introduced by the keyword across . In this example, every element of the structure my_list is printed: The local entity ic is an instance of the library class ITERATION_CURSOR . The cursor's feature item provides access to each structure element. Descendants of class ITERATION_CURSOR can be created to handle specialized iteration algorithms. The types of objects that can be iterated across ( my_list in

1357-410: Is often used as the means of traversal. The foreach statement in some languages has some defined order, processing each item in the collection from the first to the last. The foreach statement in many other languages, especially array programming languages, does not have any particular order. This simplifies loop optimization in general and in particular allows vector processing of items in

1416-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

1475-483: Is traversable using traverse ( for with its arguments flipped) and mapM ( forM with its arguments flipped) from Data.Traversable . In Java , a foreach-construct was introduced in Java Development Kit (JDK) 1.5.0. Official sources use several names for the construct. It is referred to as the "Enhanced for Loop", the "For-Each Loop", and the "foreach statement". Java also provides

1534-413: Is true if at least one item has a count greater than three: Go 's foreach loop can be used to loop over an array, slice, string, map, or channel. Using the two-value form gets the index/key (first element) and the value (second element): Using the one-value form gets the index/key (first element): Groovy supports for loops over collections like arrays, lists and ranges: Groovy also supports

1593-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

1652-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

1711-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

1770-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

1829-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

Java collections framework - Misplaced Pages Continue

1888-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

1947-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

2006-560: The ECMAScript 4.0 Standard for for each .. in which pulls the value at each index. It also supports for .. in which pulls the key at each index. Ada supports foreach loops as part of the normal for loop . Say X is an array : This syntax is used on mostly arrays, but will also work with other types when a full iteration is needed. Ada 2012 has generalized loops to foreach loops on any kind of container (array, lists, maps...): The C language does not have collections or

2065-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,

2124-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

2183-519: The actual value of the array element, not its index. Common Lisp provides foreach ability either with the dolist macro: or the powerful loop macro to iterate on more data types and even with the mapcar function: or Foreach support was added in Delphi 2005, and uses an enumerator variable that must be declared in the var section. The iteration (foreach) form of the Eiffel loop construct

2242-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

2301-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

2360-760: The collection concurrently. Syntax varies among languages. Most use the simple word for , although other use the more logical word foreach , roughly as follows: Programming languages which support foreach loops include ABC , ActionScript , Ada , C++ (since C++11 ), C# , ColdFusion Markup Language (CFML), Cobra , D , Daplex (query language), Delphi , ECMAScript , Erlang , Java (since 1.5), JavaScript , Lua , Objective-C (since 2.0), ParaSail , Perl , PHP , Prolog , Python , R , REALbasic , Rebol , Red , Ruby , Scala , Smalltalk , Swift , Tcl , tcsh , Unix shells , Visual Basic (.NET) , and Windows PowerShell . Notable languages without foreach are C , and C++ pre-C++11. ActionScript supports

2419-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;

Java collections framework - Misplaced Pages Continue

2478-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

2537-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

2596-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

2655-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

2714-497: The example) are based on classes that inherit from the library class ITERABLE . The iteration form of the Eiffel loop can also be used as a boolean expression when the keyword loop is replaced by either all (effecting universal quantification ) or some (effecting existential quantification ). This iteration is a boolean expression which is true if all items in my_list have counts greater than three: The following

2773-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

2832-481: The first two parameters. Qt , a C++ framework, offers a macro providing foreach loops using the STL iterator interface: Boost , a set of free peer-reviewed portable C++ libraries also provides foreach loops: The C++/CLI language proposes a construct similar to C#. Assuming that myArray is an array of integers: CFML incorrectly identifies the value as "index" in this construct; the index variable does receive

2891-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

2950-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

3009-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

SECTION 50

#1732782406373

3068-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

3127-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

3186-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

3245-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

3304-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

3363-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

3422-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

3481-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

#372627