Collection
Collection
t. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers).
Interfaces
The core collection interfaces encapsulate different types of collections, which are shown in the figure below. These interfaces allow collections to be manipulated independently of the details of their representation. Core collection interfaces are the foundation of the Java Collections Framework. As you can see in the following figure, the core collection interfaces form a hierarchy.
the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Collection interface is the least common denominator that all collections implement and is used to pass collections around and to manipulate them when maximum generality is desired. Some types of collections allow duplicate elements, and others do not. Some are ordered and others are unordered. The Java platform doesn't provide any direct implementations of this interface but provides implementations of more specific subinterfaces, such as Set and List.
Collection
a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the cards comprising a poker hand, the courses making up a student's schedule, or the processes running on a machine.
Set
an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position). If you've used Vector, you're familiar with the general flavor of List.
List
a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations.
Queue
Queues typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator or the elements' natural ordering. Whatever the ordering used, the head of the queue is the element that would be removed by a call to remove or poll. In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.
an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value. If you've used Hashtable, you're already familiar with the basics of Map
Map
a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls.
SortedSet
a Map that maintains its mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories.
SortedMap
The Collection Framework provides a well-designed set of interface and classes for sorting and manipulating groups of data as a single unit, a collection. The Collection Framework is made up of a set of interfaces for working with the groups of objects.
In the Collections Framework, the interfaces Map and Collection are distinct with no lineage in the hierarchy. The typical application of map is to provide access to values stored by keys.
The Collection interface is a group of objects, with duplicates allowed. Set extends Collection but forbids duplicates. List extends Collection also, allows duplicates and introduces positional indexing. Map extends neither Set nor Collection
boolean addAll(Collection c)
Adds all of the elements in the specified collection to this collection (optional operation). void clear() Removes all of the elements from this collection (optional operation).
boolean contains(Object o)
Returns true if this collection contains the specified element.
boolean containsAll(Collection c)
Returns true if this collection contains all of the elements in the specified collection.
boolean equals(Object o)
Compares the specified object with this collection for equality.
int hashCode()
Returns the hash code value for this collection.
boolean isEmpty()
Returns true if this collection contains no elements.
Iterator iterator() Returns an iterator over the elements in this collection. boolean remove(Object o)
Removes a single instance of the specified element from this collection, if it is present (optional operation). Removes all this collection's elements that are also contained in the specified collection (optional operation).
boolean removeAll(Collection c)
boolean retainAll(Collection c)
Retains only the elements in this collection that are contained in the specified collection (optional operation). Returns the number of elements in this collection.
int size()
Object[] toArray() Returns an array containing all of the elements in this collection. Object[] toArray(Object[] a) Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. The interface supports basic operations like adding and removing. When you try to remove an element, only a single instance of the element in the collection is removed, if present.
boolean remove(Object o)
The Collection interface also supports query operations int size() boolean isEmpty() boolean contains(Object o) Iterator iterator(
Java Collection Framework - Iterator Interface The iterator () method of the Collection interface returns and Iterator. An Iterator is similar to the Enumeration interface, Iterators differ from enumerations in two ways: 1. Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. 2. Method names have been improved. Boolean hasNext() : Returns true if the iteration has more elements. Object next() : Returns the next element in the iteration. Void remove() : Removes from the underlying collection the last element returned by the iterator (optional operation). The remove method is optionally suported by the underlying collection. When called and supported, the element returned by the last next() call is removed. Java Collection Framework - Set Interface The set interface extends the Collection interface and, by definition, forbids duplicates within the collection. All the original methods are present and no new method is introduced. The concrete Set implementation classes rely on the equals() method of the object added to check for equality. Boolean add (Object o) : Ensures that this collection contains the specified element (optional operation). Boolean addAll(Collection c) : Adds all of the elements in the specified collection to this collection (optional operation). Void clear() : Removes all of the elements from this collection (optional operation). Boolean contains(Object o) : Returns true if this collection contains the specified element. Boolean containsAll(Collection c) : Returns true if this collection contains all of the elements in the specified collection.
Boolean equals(Object o) : Compares the specified object with this collection for equality. Int hashCode() : Returns the hash code value for this collection. Boolean isEmpty() : Returns true if this collection contains no elements. Iterator iterator() : Returns an iterator over the elements in this collection. Boolean remove(Object o) : Removes a single instance of the specified element from this collection, if it is present (optional operation). Boolean removeAll(Collection c) : Removes all this collection's elements that are also contained in the specified collection (optional operation). Boolean retainAll(Collection c) : Retains only the elements in this collection that are contained in the specified collection (optional operation). Int size() : Returns the number of elements in this collection. Object[] toArray() : Returns an array containing all of the elements in this collection. Object[] toArray(Object[] a) : Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. Java Collection Framework - List Interface This is an ordered collection (also known as a sequence). The List interface extends the Collection interface to define an ordered collection, permitting duplicates. The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Void add(int index, Object element) : Inserts the specified element at the specified position in this list (optional operation). Boolean add(Object o) : Appends the specified element to the end of this list (optional operation). Boolean addAll(Collection c) : Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation). Boolean addAll(int index, Collection c) : Inserts all of the elements in the specified collection into this list at the specified position ( optional operation). Void clear() : Removes all of the elements from this list (optional operation). Boolean contains(Object o) : Returns true if this list contains the specified element.
Boolean containsAll(Collection c): Returns true if this list contains all of the elements of the specified collection. Boolean equals(Object o) : Compares the specified object with this list for equality. Object get(int index) : Returns the element at the specified position in this list. Int hashCode() : Returns the hash code value for this list. Int indexOf(Object o) : Returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element. Boolean isEmpty() : Returns true if this list contains no elements. Iterator iterator() : Returns an iterator over the elements in this list in proper sequence. Int lastIndexOf(Object o) : Returns the index in this list of the last occurrence of the specified element, or -1 if this list does not contain this element. ListIterator listIterator() : Returns a list iterator of the elements in this list (in proper sequence). ListIterator listIterator(int index): Returns a list iterator of the elements in this list (in proper sequence), starting at the specified position in this list. Object remove(int index) : Removes the element at the specified position in this list (optional operation). Boolean remove(Object o) : Removes the first occurrence in this list of the specified element (optional operation). Boolean removeAll(Collection c) : Removes from this list all the elements that are contained in the specified collection (optional operation). Boolean retainAll(Collection c) : Retains only the elements in this list that are contained in the specified collection (optional operation). Object set(int index, Object element) : Replaces the element at the specified position in this list with the specified element (optional operation). Int size() : Returns the number of elements in this list. List subList(int fromIndex, int toIndex) : Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. Object[] toArray() : Returns an array containing all of the elements in this list in proper sequence.
Object[] toArray(Object[] a) : Returns an array containing all of the elements in this list in proper sequence; the runtime type of the returned array is that of the specified array. Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare. The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience. The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation. The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list. The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches. The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list. Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on a such a list. Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.
int indexOf(Object o) Returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element. boolean isEmpty() Returns true if this list contains no elements. Iterator iterator() Returns an iterator over the elements in this list in proper sequence. int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element, or -1 if this list does not contain this element. ListIterator listIterator() Returns a list iterator of the elements in this list (in proper sequence). ListIterator listIterator(int index) Returns a list iterator of the elements in this list (in proper sequence), starting at the specified position in this list. Object remove(int index) Removes the element at the specified position in this list (optional operation). boolean remove(Object o) Removes the first occurrence in this list of the specified element (optional operation). boolean removeAll(Collection c) Removes from this list all the elements that are contained in the specified collection (optional operation). boolean retainAll(Collection c) Retains only the elements in this list that are contained in the specified collection (optional operation). Object set(int index, Object element) Replaces the element at the specified position in this list with the specified element (optional operation). int size() Returns the number of elements in this list. List subList(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. Object[] toArray() Returns an array containing all of the elements in this list in proper sequence.
Object[] toArray(Object[] a) Returns an array containing all of the elements in this list in proper sequence; the runtime type of the returned array is that of the specified array.
The add(0 operation requires a little bit of explanation, also Adding an element results in the new element being added immediately prior to the implicit cursor. This calling preious after adding an element would return the new element and calling next would have no effect, returning what would hav been the next element prior to the add operation.
defination. The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not. void clear() Removes all mappings from this map (optional operation).
boolean equals(Object o)
Compares the specified object with this map for equality. Object get(Object key) Returns the value to which this map maps the specified key.
int hashCode()
Returns the hash code value for this map.
boolean isEmpty()
Returns true if this map contains no key-value mappings. Set keySet() Returns a set view of the keys contained in this map. Object put(Object key, Object value) Associates the specified value with the specified key in this map (optional operation). void putAll(Map t) Copies all of the mappings from the specified map to this map (optional operation). Object remove(Object key) Removes the mapping for this key from this map if it is present (optional operation).
int size()
Returns the number of key-value mappings in this map. Returns a collection view of the values contained in this map.
Collection values()
The interface methods can be broken down into three sets of operations: altering, querying and providing alternative views The alteration operation allows you to add and remove key-value pairs from the map. Both the key and value can be null. However you should not add a Map to itself as a key or value. Object put(Object key, Object value) Object remove(Object key)
void putAll(Map t) void clear() The query operations allow you to check on the contents of the map Object get(Object key) boolean containsKey(Object key) boolean containsValue(Object value) int size() boolean isEmpty() The set methods allow you to work with the group ofkeys or values as a collection Set keySet() Collection values() Set entrySet()
This example uses the reverse order Comprator available from the Collection calss. Comparator comparator= Collections.reverseOrder(); Set reverseSer= new TreeSet(comparator); revereseSet.add("one"); revereseSet.add("two"); revereseSet.add("three"); revereseSet.add("four"); revereseSet.add("one"); System.out.println(reverseSet); Output of this program [two, three, one, four]
Returns a view of the portion of this sorted map whose keys range from fromKey, inclusive, to toKey, exclusive. Returns a view of the portion of this sorted map whose keys are greater than or equal to fromKey.
codes. While most system classes override the default hashCode() implementation of the Object, when creating your own class to add to a HashSet remember to override hashCode(). The TreeSet implementations useful when you need to extract elements from a collection in a sorted manner. It is generally faster to add elements to the HasSet then convert the collection to a TreeeSet for sorted traversal. To optimize HashSet space usage , you can tune initial capacity and load factor. TreeSet has no tuning options, as the tree is always balanced, ensuring log(n0 performance for insertions, deletions and queries. Example import java.util.*; public class HashTreeSetEx{ public static void main (String args[]){ Set set = new HashSet(){ set.add("one"); set.add("two"); set.add("three"); set.add("four"); set.add("one"); System.out.println(set); Set sortedSet= new TreeSet(set); System.out.println(SortedSet); } } } The program produces the following output. The duplicate entry is olypresent once and the second line outputs sorted [one, two, three, four] [four, one, three, two] Note that these implementation is not synchronized. If multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set: Set s = Collections.synchronizedSet(new HashSet(...)); SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));
the optimal collection, the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost. An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation. Note that these implementation is not synchronized. If multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set: List list = Collections.synchronizedList(new LinkedList(...)); List list = Collections.synchronizedList(new ArrayList(...));
concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set: Map m = Collections.synchronizedMap(new HashMap(...)); Map m = Collections.synchronizedMap(new TreeMap(...));