0% found this document useful (0 votes)
27 views

Collection

The document discusses key interfaces in the Java Collections Framework. It describes the Collection interface as the root interface representing a group of objects. Sets forbid duplicates while Lists are ordered and allow duplicates. Maps map keys to values without duplicates. The interfaces provide common operations like adding, removing and querying elements in a collection.

Uploaded by

Gaurav Singh
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Collection

The document discusses key interfaces in the Java Collections Framework. It describes the Collection interface as the root interface representing a group of objects. Sets forbid duplicates while Lists are ordered and allow duplicates. Maps map keys to values without duplicates. The interfaces provide common operations like adding, removing and querying elements in a collection.

Uploaded by

Gaurav Singh
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 15

A collection sometimes called a container is simply an object that groups multiple elements into a single unit.

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

Interface Set List Map HashMap HashSet

Implementation TreeSet ArrayList Treemap LinkedList

Historical Vector Stack Hashtable Properties

Java Collection Framework - Collection Interface


The Collection interface is used to represent any group of ojects, or elements. Here is a list of the public methods of the Collection Interface. 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). 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 add (Object o)

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.

Java Collection Framework - ListIterator Interface


The ListIterator interface extends the Iterator interface to support bi-directional access as well as adding or removing or changing elements in the underlying collection. An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). In a list of length n, there are n+1 valid index values, from 0 to n, inclusive. 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.

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.

Java Collection Framework - Map Interface


The Map interface is not an extension of Collection interface. Instead the interface starts of its own interface hierarchy, for maintaining key-value associations. The interface describes a mapping from keys to values, without duplicate keys, by

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 containsKey(Object key)


Returns true if this map contains a mapping for the specified key.

boolean containsValue(Object value)


Returns true if this map maps one or more keys to the specified value. Set entrySet() Returns a set view of the mappings contained in this map.

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()

Java Collection Framework - SortedSet Interface


The Collection Framework provides a special Set interface for maintaining elements in a sorted order called SortedSet. Comparator comparator() Returns the comparator associated with this sorted set, or null if it uses its elements' natural ordering. Object first() Returns the first (lowest) element currently in this sorted set. SortedSet headSet(Object toElement) Returns a view of the portion of this sorted set whose elements are strictly less than toElement. Object last() Returns the last (highest) element currently in this sorted set. SortedSet subSet(Object fromElement, Object toElement) Returns a view of the portion of this sorted set whose elements range from fromElement, inclusive, to toElement, exclusive. SortedSet tailSet(Object fromElement) Returns a view of the portion of this sorted set whose elements are greater than or equal to fromElement. The interface provides access methods to the ends of the set as well to subsets of the set. When working with subsets of the list, changes to the subset are reflected in the source set. In addition changes to the source set are reflected in the subset. This works because subsets are identical by elements at the end point, not indices. In addition , if the formElement is part of the source set , it is part of the subset. However, if the toElement is part of the source ser, it is not part of the subset. If you would like a particular to-element to be in the subset, you must find the next element. In the case of a string, the next element is the same strong with a null character appended (string+\0).; The element added to a SortedSet must either implement Comparable or you must provide a Comparator to the constructor to its implementation class: TreeSet.

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]

Java Collection Framework - Sorted Map Interface


The Collection Framework provides a special Map interface for maintaining elements in a sorted order called SortedMap. The interface provides access methods to the ends of the map as well to subsets of the set. Working with a SortedMap is just like a SortedSet, except the sort is done on the map keys. The implementation class provided by the Collection Framework is a TreeMap. Comparator comparator() Returns the comparator associated with this sorted map, or null if it uses its keys' natural ordering. Object firstKey() Returns the first (lowest) key currently in this sorted map.

SortedMap headMap(Object toKey)


Returns a view of the portion of this sorted map whose keys are strictly less than toKey. Object lastKey() Returns the last (highest) key currently in this sorted map.

SortedMap subMap(Object fromKey, Object toKey)

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.

SortedMap tailMap(Object fromKey)

Java Collection Framework - HashSet & TreeSet Classes


The Collection Framework provides two general purpose implementations often Set interface, HashSet and TreeSet. More often than not you will use a HashSet for storing your duplicate-free collection. For efficiency objects added to a HashSet need to implement the hashCode() method in a manner that properly distributes the hash

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(...));

Java Collection Framework - ArrayList & LinkedList Classes


There are two general-purpose List implementations in the Collection Framework, ArrayList and LinkedList, which of the two List implementations you use depends on your specific needs. If you need to support random access, without inserting or removing elements from any place to other than the end, then ArrayList offers you

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(...));

Java Collection Framework - HashMap & TreeMap Classes


The Collection Framework provides two general-purpose Map implementation: HashMap and TreeMap. As with all the concrete implementations, which implement you use depends on your specific needs. For inserting, deleting and locating elements in a Map the HashMap offers best alternatively. If however you need to traverse the keys in a sorted order then TreeMap is better alternative. Depending upon your size of your collection, it may be faster to add elements to a HashMap then convert the Map to a TreeMap for sorted key traversal. Using a HashMap requires that the class of key added have a well-defined hashCode() implementation. With the TreeMap implementation elements added to the Map must be sortable. To optimize HashMap usage you can tune the initial capacity and load factor. The TreeMap has no tuning options as the tree is always balanced An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the capacity is roughly doubled by calling the rehash method. As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur. 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: Map m = Collections.synchronizedMap(new HashMap(...)); Map m = Collections.synchronizedMap(new TreeMap(...));

Java Collection Framework- Vector & Stack Classes


A Vector is an historical collection class that acts like a growable array, but can store heterogeneous data elements. Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation. The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty, and a method to search the stack for an item and discover how far it is from the top.

You might also like