A collection sometimes called a container is simply an object that groups multiple elements into a single unit. 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.
A Set is a special kind of Collection, a SortedSet is a special kind of Set, and so forth. Note also that the hierarchy consists of two distinct trees a Map is not a true Collection.
Note that all the core collection interfaces are generic. For example, this is the declaration of the
Collection interface. public interface Collection<E>...
The <E> syntax tells you that the interface is generic. When you declare a Collection instance you can and should specify the type of object contained in the collection. Specifying the type allows the
1
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
compiler to verify (at compile-time) that the type of object you put into the collection is correct, thus reducing errors at runtime. The following list describes the core collection interfaces:
y
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. Set 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. See also The Set Interface section. List 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. Queue a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations.
Collection
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.
Map 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.
The last two core collection interfaces are merely sorted versions of Set and Map:
y SortedSet
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. SortedMap 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.
2
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework A Collection represents a group of objects known as its elements. The Collection interface is used to pass around collections of objects where maximum generality is desired. For example, by convention all general-purpose collection implementations have a constructor that takes a Collection argument. This constructor, known as a conversion constructor, initializes the new collection to contain all of the elements in the specified collection, whatever the given collection's subinterface or implementation type. In other words, it allows you to convert the collection's type.
Suppose, for example, that you have a Collection<String> c, which may be a List, a Set, or another kind of Collection. This idiom creates a new ArrayList (an implementation of the List interface), initially containing all the elements in c.
List<String> list = new ArrayList<String>(c); The following shows the Collection interface. public interface Collection<E> extends Iterable<E> { // Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator(); // Bulk operations boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); //optional boolean removeAll(Collection<?> c); //optional boolean retainAll(Collection<?> c); //optional void clear(); //optional // Array operations Object[] toArray(); <T> T[] toArray(T[] a); }
The interface does about what you'd expect given that a Collection represents a group of objects. The interface has methods to tell you how many elements are in the collection (size, isEmpty), to check whether a given object is in the collection (contains), to add and remove an element from the collection (add, remove), and to provide an iterator over the collection (iterator).
The add method is defined generally enough so that it makes sense for collections that allow duplicates as well as those that don't. It guarantees that the Collection will contain the specified element after the call completes, and returns true if the Collection changes as a result of the call. Similarly, the remove method is designed to remove a single instance of the specified element from the Collection, assuming that it contains the element to start with, and to return true if the Collection was modified as a result.
Traversing Collections There are two ways to traverse collections: (1) with the for-each construct and (2) by using Iterators.
3
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework for-each Construct The for-each construct allows you to concisely traverse a collection or array using a for loop . The following code uses the for-each construct to print out each element of a collection on a separate line.
for (Object o : collection) System.out.println(o);
Iterators An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired. You get an Iterator for a collection by calling its iterator method. The following is the Iterator interface.
public interface Iterator<E> { boolean hasNext(); E next(); void remove(); //optional } The hasNext method returns true if the iteration has more elements, and the next method returns the next
element in the iteration. The remove method removes the last element that was returned by next from the underlying Collection. The remove method may be called only once per call to next and throws an exception if this rule is violated.
Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress. Use Iterator instead of the for-each construct when you need to:
y y
Remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering. Iterate over multiple collections in parallel. that is,
The following method shows you how to use an Iterator to filter an arbitrary Collection traverse the collection removing specific elements.
static void filter(Collection<?> c) { for (Iterator<?> it = c.iterator(); it.hasNext(); ) if (!cond(it.next())) it.remove(); }
This simple piece of code is polymorphic, which means that it works for any Collection regardless of implementation. This example demonstrates how easy it is to write a polymorphic algorithm using the Java Collections Framework.
Collection Interface Bulk Operations Bulk operations perform an operation on an entire Collection. You could implement these shorthand operations using the basic operations, though in most cases such implementations would be less efficient. The following are the bulk operations: 4
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
The addAll, removeAll, and retainAll methods all return true if the target Collection was modified in the process of executing the operation.
As a simple example of the power of bulk operations, consider the following idiom to remove all instances of a specified element, e, from a Collection, c.
c.removeAll(Collections.singleton(e));
More specifically, suppose you want to remove all of the null elements from a Collection.
c.removeAll(Collections.singleton(null)); This idiom uses Collections.singleton, which is a static factory method that returns an immutable Set
Collection Interface Array Operations The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input. The array operations allow the contents of a Collection to be translated into an array. The simple form with no arguments creates a new array of Object. The more complex form allows the caller to provide an array or to choose the runtime type of the output array.
For example, suppose that c is a Collection. The following snippet dumps the contents of c into a newly allocated array of Object whose length is identical to the number of elements in c.
Object[] a = c.toArray(); Suppose that c is known to contain only strings (perhaps because c is of type Collection<String>). The
following snippet dumps the contents of c into a newly allocated array of String whose length is identical to the number of elements in c.
String[] a = c.toArray(new String[0]);
The Java platform contains three general-purpose Set implementations: HashSet, TreeSet, and LinkedHashSet.
HashSet, which stores its elements in a hash table, is the best-performing implementation; however it makes
elements based on the order in which they were inserted into the set (insertion-order).
6
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
The offer method, which is intended solely for use on bounded queues, differs from add only in that it indicates failure to insert an element by returning false.
The remove and poll methods both remove and return the head of the queue. Exactly which element gets removed is a function of the queue's ordering policy. The remove and poll methods differ in their behavior only when the queue is empty. Under these circumstances, remove throws NoSuchElementException, while poll returns null. The element and peek methods return, but do not remove, the head of the queue. They differ from one another in precisely the same fashion as remove and poll: If the queue is empty, element throws NoSuchElementException, while peek returns null.
7
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
The Java platform contains three general-purpose Map implementations: HashMap, TreeMap, and LinkedHashMap. Their behavior and performance are precisely analogous to HashSet, TreeSet, and
LinkedHashSet.
Object Ordering
A List l may be sorted as follows.
Collections.sort(l); If the List consists of String elements, it will be sorted into alphabetical order. If it consists of Date
elements, it will be sorted into chronological order. How does this happen? String and Date both implement the Comparable interface. Comparable implementations provide a natural ordering for a class, which allows objects of that class to be sorted automatically. The following table summarizes some of the more important Java platform classes that implement Comparable. Classes Implementing Comparable Class
Byte Character
8
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Signed numerical Signed numerical Signed numerical Signed numerical Signed numerical Signed numerical Signed numerical
Boolean.FALSE < Boolean.TRUE
If you try to sort a list, the elements of which do not implement Comparable, Collections.sort(list) will throw a ClassCastException. Similarly, Collections.sort(list, comparator) will throw a ClassCastException if you try to sort a list whose elements cannot be compared to one another using the comparator. Elements that can be compared to one another are called mutually comparable. Although elements of different types may be mutually comparable, none of the classes listed here permit interclass comparison. This is all you really need to know about the Comparable interface if you just want to sort lists of comparable elements or to create sorted collections of them. The next section will be of interest to you if you want to implement your own Comparable type.
Writing Your Own Comparable Types The Comparable interface consists of the following method.
public interface Comparable<T> { public int compareTo(T o); } The compareTo method compares the receiving object with the specified object and returns a negative
integer, 0, or a positive integer depending on whether the receiving object is less than, equal to, or greater 9
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework than the specified object. If the specified object cannot be compared to the receiving object, the method throws a ClassCastException.
Comparators
What if you want to sort some objects in an order other than their natural ordering? Or what if you want to sort some objects that don't implement Comparable? To do either of these things, you'll need to provide a Comparator an object that encapsulates an ordering. Like the Comparable interface, the Comparator interface consists of a single method. 10
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
depending on whether the first argument is less than, equal to, or greater than the second. If either of the arguments has an inappropriate type for the Comparator, the compare method throws a ClassCastException.
Much of what was said about Comparable applies to Comparator as well. Writing a compare method is nearly identical to writing a compareTo method, except that the former gets both objects passed in as arguments. The compare method has to obey the same four technical restrictions as Comparable's compareTo method for the same reason a Comparator must induce a total order on the objects it compares. Suppose you have a class called Employee, as follows.
public class Employee implements Comparable<Employee> { public Name name() { ... } public int number() { ... } public Date hireDate() { ... } ... } Let's assume that the natural ordering of Employee instances is Name ordering (as defined in the previous
example) on employee name. Unfortunately, the boss has asked for a list of employees in order of seniority. This means we have to do some work, but not much. The following program will produce the required list.
import java.util.*; public class EmpSort { static final Comparator<Employee> SENIORITY_ORDER = new Comparator<Employee>() { public int compare(Employee e1, Employee e2) { return e2.hireDate().compareTo(e1.hireDate()); } }; // Employee database static final Collection<Employee> employees = ... ; public static void main(String[] args) { List<Employee>e = new ArrayList<Employee>(employees); Collections.sort(e, SENIORITY_ORDER); System.out.println(e); } }
Interface NavigableSet
A SortedSet extended with navigation methods reporting closest matches for given search targets.
Method Summary
E ceiling(E e) Returns the least element in this set greater than or equal to the given element, or null if there is no such element. Iterator<E> descendingIterator() Returns an iterator over the elements in this set, in descending order. NavigableSet<E> descendingSet() Returns a reverse order view of the elements contained in this set. E floor(E e) Returns the greatest element in this set less than or equal to the given element, or null if there is no such element. SortedSet<E> headSet(E toElement) Returns a view of the portion of this set whose elements are strictly less than toElement. NavigableSet<E> headSet(E toElement, boolean inclusive) Returns a view of the portion of this set whose elements are less than (or equal to, if inclusive is true) toElement. E higher(E e) Returns the least element in this set strictly greater than the given element, or null if there is no such element. Iterator<E> iterator() Returns an iterator over the elements in this set, in ascending order.
12
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework E lower(E e) Returns the greatest element in this set strictly less than the given element, or null if there is no such element. E pollFirst() Retrieves and removes the first (lowest) element, or returns null if this set is empty. E pollLast() Retrieves and removes the last (highest) element, or returns null if this set is empty. NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement,
boolean toInclusive)
Returns a view of the portion of this set whose elements range from fromElement to toElement. SortedSet<E> subSet(E fromElement, E toElement) Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive. SortedSet<E> tailSet(E fromElement) Returns a view of the portion of this set whose elements are greater than or equal to fromElement. NavigableSet<E> tailSet(E fromElement, boolean inclusive) Returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.
The Java Collections Framework provides several general-purpose implementations of the core interfaces: y y y y For the Set interface, HashSet is the most commonly used implementation. For the List interface, ArrayList is the most commonly used implementation. For the Map interface, HashMap is the most commonly used implementation. For the Queue interface, LinkedList is the most commonly used implementation.
13
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Interface Collection<E>
public interface Collection<E> extends Iterable<E>
Method Summary
boolean add(E e)
Ensures that this collection contains the specified element (optional operation).
boolean addAll(Collection<? extends E> c)
Adds all of the elements in the specified collection to this collection (optional operation).
void clear()
Returns true if this collection contains all of the elements in the specified collection.
boolean equals(Object o)
Returns true if this collection contains no elements. Iterator<E 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).
14
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Removes all of 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.
<T> T[] toArray(T[] 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.util
Class AbstractCollection<E>
public abstract class AbstractCollection<E> extends Object implements Collection<E>
This class provides a skeletal implementation of the Collection interface, to minimize the effort required to implement this interface.
java.util
Class AbstractSet<E>
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E>
This class provides a skeletal implementation of the Set interface to minimize the effort required to implement this interface.
java.util
Class AbstractList<E>
public abstract class AbstractList<E> extends AbstractCollection<E>
15
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array). For sequential access data (such as a linked list), AbstractSequentialList should be used in preference to this class.
Method Summary
boolean add(E e)
Appends the specified element to the end of this list (optional operation).
void add(int index, E element)
Inserts the specified element at the specified position in this list (optional operation).
boolean addAll(int index, Collection<? extends E> c)
Inserts all of the elements in the specified collection into this list at the specified position (optional operation).
void clear()
E get(int index) Returns the element at the specified position in this list.
int hashCode()
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Iterator<E> iterator() Returns an iterator over the elements in this list in proper sequence.
int lastIndexOf(Object o)
Returns the index of the last occurrence of the specified element in this list, or -1 if this 16
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework list does not contain the element. ListIterator<E> listIterator() Returns a list iterator over the elements in this list (in proper sequence). ListIterator<E> listIterator(int index) Returns a list iterator of the elements in this list (in proper sequence), starting at the specified position in this list. E remove(int index) Removes the element at the specified position in this list (optional operation).
protected removeRange(int fromIndex, int toIndex) void Removes from this list all of the elements whose index is between fromIndex,
inclusive, and toIndex, exclusive. E set(int index, E element) Replaces the element at the specified position in this list with the specified element (optional operation). List<E> subList(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
java.util
Class AbstractQueue<E>
public abstract class AbstractQueue<E> extends AbstractCollection<E> implements Queue<E>
Method Summary
boolean add(E e)
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an
17
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Removes all of the elements from this queue. E element() Retrieves, but does not remove, the head of this queue. E remove() Retrieves and removes the head of this queue.
A linear collection that supports element insertion and removal at both ends.
Method Summary
boolean add(E e)
Inserts the specified element into the queue represented by this deque (in other words, at the tail of this deque) if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
void addFirst(E e)
Inserts the specified element at the front of this deque if it is possible to do so immediately without violating capacity restrictions.
void addLast(E e)
Inserts the specified element at the end of this deque if it is possible to do so immediately without violating capacity restrictions.
boolean
contains(Object o) 18
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework Returns true if this deque contains the specified element. Iterator<E> descendingIterator() Returns an iterator over the elements in this deque in reverse sequential order. E element() Retrieves, but does not remove, the head of the queue represented by this deque (in other words, the first element of this deque). E getFirst() Retrieves, but does not remove, the first element of this deque. E getLast() Retrieves, but does not remove, the last element of this deque. Iterator<E> iterator() Returns an iterator over the elements in this deque in proper sequence.
boolean offer(E e)
Inserts the specified element into the queue represented by this deque (in other words, at the tail of this deque) if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.
boolean offerFirst(E e)
Inserts the specified element at the front of this deque unless it would violate capacity restrictions.
boolean offerLast(E e)
Inserts the specified element at the end of this deque unless it would violate capacity restrictions. E peek() Retrieves, but does not remove, the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty. E peekFirst() Retrieves, but does not remove, the first element of this deque, or returns null if this deque is empty.
19
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework E peekLast() Retrieves, but does not remove, the last element of this deque, or returns null if this deque is empty. E poll() Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty. E pollFirst() Retrieves and removes the first element of this deque, or returns null if this deque is empty. E pollLast() Retrieves and removes the last element of this deque, or returns null if this deque is empty. E pop() Pops an element from the stack represented by this deque.
void push(E e)
Pushes an element onto the stack represented by this deque (in other words, at the head of this deque) if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available. E remove() Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque).
boolean remove(Object o)
Removes the first occurrence of the specified element from this deque. E removeFirst() Retrieves and removes the first element of this deque.
boolean removeFirstOccurrence(Object o)
Removes the first occurrence of the specified element from this deque. E removeLast() 20
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework Retrieves and removes the last element of this deque.
boolean removeLastOccurrence(Object o)
Removes the last occurrence of the specified element from this deque.
int size()
java.util
Class ArrayDeque<E>
public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable, Serializable
Resizable-array implementation of the Deque interface. Array deques have no capacity restrictions; they grow as necessary to support usage. They are not thread-safe; in the absence of external synchronization, they do not support concurrent access by multiple threads. Null elements are prohibited.
Set hierarchy
Queue hierarchy
21
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
java.util
Class HashSet<E>
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
22
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Note that this implementation is not synchronized. If multiple threads access a hash 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(...));
Constructor Summary
HashSet() Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75). HashSet(Collection<? extends E> c) Constructs a new set containing the elements in the specified collection. HashSet(int initialCapacity) Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75). HashSet(int initialCapacity, float loadFactor) Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.
The load factor is a measure of how full the hash map/table is allowed to get before its capacity is automatically increased. When the number of entries in the hashmap/table exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method.
java.util
Class TreeSet<E>
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable
23
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used. Note that this implementation is not synchronized. The TreeSet is the other available Set implementation. As the name implies, it is backed by a (balanced) tree data structure. If ordering is important, then TreeSet is the set collection of choice.
Constructor Summary
TreeSet() Constructs a new, empty tree set, sorted according to the natural ordering of its elements. TreeSet(Collection<? extends E> c) Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements. TreeSet(Comparator<? super E> comparator) Constructs a new, empty tree set, sorted according to the specified comparator. TreeSet(SortedSet<E> s) Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.
Method Summary
boolean add(E e)
Adds all of the elements in the specified collection to this set. E ceiling(E e) Returns the least element in this set greater than or equal to the given element, or null if there is no such element.
void
clear() 24
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework Removes all of the elements from this set. Object clone() Returns a shallow copy of this TreeSet instance. Comparator<? comparator() super E> Returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.
boolean contains(Object o)
Returns true if this set contains the specified element. Iterator<E> descendingIterator() Returns an iterator over the elements in this set in descending order. NavigableSet<E> descendingSet() Returns a reverse order view of the elements contained in this set. E first() Returns the first (lowest) element currently in this set. E floor(E e) Returns the greatest element in this set less than or equal to the given element, or null if there is no such element. SortedSet<E> headSet(E toElement) Returns a view of the portion of this set whose elements are strictly less than toElement. NavigableSet<E> headSet(E toElement, boolean inclusive) Returns a view of the portion of this set whose elements are less than (or equal to, if inclusive is true) toElement. E higher(E e) Returns the least element in this set strictly greater than the given element, or null if there is no such element.
boolean isEmpty()
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework Iterator<E> iterator() Returns an iterator over the elements in this set in ascending order. E last() Returns the last (highest) element currently in this set. E lower(E e) Returns the greatest element in this set strictly less than the given element, or null if there is no such element. E pollFirst() Retrieves and removes the first (lowest) element, or returns null if this set is empty. E pollLast() Retrieves and removes the last (highest) element, or returns null if this set is empty.
boolean remove(Object o)
Returns the number of elements in this set (its cardinality). NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement,
boolean toInclusive)
Returns a view of the portion of this set whose elements range from fromElement to toElement. SortedSet<E> subSet(E fromElement, E toElement) Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive. SortedSet<E> tailSet(E fromElement) Returns a view of the portion of this set whose elements are greater than or equal to fromElement. NavigableSet<E> tailSet(E fromElement, boolean inclusive) Returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.
26
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework See Example - TreeSetDemo.java
java.util
Class LinkedHashSet<E>
public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. Note that this implementation is not synchronized.
Constructor Summary
LinkedHashSet() Constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75). LinkedHashSet(Collection<? extends E> c) Constructs a new linked hash set with the same elements as the specified collection. LinkedHashSet(int initialCapacity) Constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75). LinkedHashSet(int initialCapacity, float loadFactor) Constructs a new, empty linked hash set with the specified initial capacity and load factor.
Method Summary
27
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework Methods inherited from class java.util.AbstractSet
equals, hashCode, removeAll
java.util
Class ArrayList<E>
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. 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 this implementation is not synchronized.
28
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Constructor Summary
ArrayList() Constructs an empty list with an initial capacity of ten. ArrayList(Collection<? extends E> c) Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. ArrayList(int initialCapacity) Constructs an empty list with the specified initial capacity.
Method Summary
boolean add(E e)
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.
boolean addAll(int index, Collection<? extends E> c)
Inserts all of the elements in the specified collection into this list, starting at the specified position.
void clear()
Removes all of the elements from this list. Object clone() Returns a shallow copy of this ArrayList instance.
boolean
contains(Object o) 29
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework Returns true if this list contains the specified element.
void ensureCapacity(int minCapacity)
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. E get(int index) Returns the element at the specified position in this list.
int indexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
boolean isEmpty()
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. E remove(int index) Removes the element at the specified position in this list.
boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present.
protected removeRange(int fromIndex, int toIndex) void Removes from this list all of the elements whose index is between fromIndex, inclusive,
and toIndex, exclusive. E set(int index, E element) Replaces the element at the specified position in this list with the specified element.
int size()
Returns the number of elements in this list. Object[] toArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element). 30
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.
java.util
Class Vector<E>
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.
Constructor Summary
Vector() Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero. Vector(Collection<? extends E> c) Constructs a vector containing the elements of the specified collection, in the order they are returned by the collection's iterator. Vector(int initialCapacity) Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero. Vector(int initialCapacity, int capacityIncrement) Constructs an empty vector with the specified initial capacity and capacity increment.
capacityIncrement - The amount by which the capacity of the vector is automatically incremented when
31
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework its size becomes greater than its capacity. If the capacity increment is less than or equal to zero, the capacity of the vector is doubled each time it needs to grow.
Method Summary
boolean add(E e)
Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified Collection's Iterator.
boolean addAll(int index, Collection<? extends E> c)
Inserts all of the elements in the specified Collection into this Vector at the specified position.
void addElement(E obj)
Adds the specified component to the end of this vector, increasing its size by one.
int capacity()
Removes all of the elements from this Vector. Object clone() Returns a clone of this vector.
boolean contains(Object o)
Returns true if this Vector contains all of the elements in the specified Collection. 32
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Copies the components of this vector into the specified array. E elementAt(int index) Returns the component at the specified index. Enumeration<E> elements() Returns an enumeration of the components of this vector.
void ensureCapacity(int minCapacity)
Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.
boolean equals(Object o)
Compares the specified Object with this Vector for equality. E firstElement() Returns the first component (the item at index 0) of this vector. E get(int index) Returns the element at the specified position in this Vector.
int hashCode()
Returns the index of the first occurrence of the specified element in this vector, or -1 if this vector does not contain the element.
int indexOf(Object o, int index)
Returns the index of the first occurrence of the specified element in this vector, searching forwards from index, or returns -1 if the element is not found.
void insertElementAt(E obj, int index)
Inserts the specified object as a component in this vector at the specified index.
boolean isEmpty()
33
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework E lastElement() Returns the last component of the vector.
int lastIndexOf(Object o)
Returns the index of the last occurrence of the specified element in this vector, or -1 if this vector does not contain the element.
int lastIndexOf(Object o, int index)
Returns the index of the last occurrence of the specified element in this vector, searching backwards from index, or returns -1 if the element is not found. E remove(int index) Removes the element at the specified position in this Vector.
boolean remove(Object o)
Removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged.
boolean removeAll(Collection<?> c)
Removes from this Vector all of its elements that are contained in the specified Collection.
void removeAllElements()
Removes all components from this vector and sets its size to zero.
boolean removeElement(Object obj)
Removes the first (lowest-indexed) occurrence of the argument from this vector.
void removeElementAt(int index)
Retains only the elements in this Vector that are contained in the specified Collection. E set(int index, E element) 34
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework Replaces the element at the specified position in this Vector with the specified element.
void setElementAt(E obj, int index)
Sets the component at the specified index of this vector to be the specified object.
void setSize(int newSize)
Returns the number of components in this vector. List<E> subList(int fromIndex, int toIndex) Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive. Object[] toArray() Returns an array containing all of the elements in this Vector in the correct order.
<T> T[] toArray(T[] a)
Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array. String toString() Returns a string representation of this Vector, containing the String representation of each element.
void trimToSize()
java.util
Class Stack<E>
public class Stack<E> extends Vector<E>
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,
35
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
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. When a stack is first created, it contains no items.
Constructor Summary
Stack() Creates an empty Stack.
Method Summary
boolean empty()
Tests if this stack is empty. E peek() Looks at the object at the top of this stack without removing it from the stack. E pop() Removes the object at the top of this stack and returns that object as the value of this function. E push(E item) Pushes an item onto the top of this stack.
int search(Object o)
java.util
Class LinkedList<E>
Linked list implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface, the LinkedList class
36
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue. The class implements the Deque interface, providing first-in-first-out queue operations for add, poll, along with other stack and deque operations.
Constructor Summary
LinkedList() Constructs an empty list. LinkedList(Collection<? extends E> c) Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
Method Summary
boolean add(E e)
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.
boolean addAll(int index, Collection<? extends E> c)
Inserts all of the elements in the specified collection into this list, starting at the specified position.
void addFirst(E e)
37
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Removes all of the elements from this list. Object clone() Returns a shallow copy of this LinkedList.
boolean contains(Object o)
Returns true if this list contains the specified element. Iterator<E> descendingIterator() Returns an iterator over the elements in this deque in reverse sequential order. E element() Retrieves, but does not remove, the head (first element) of this list. E get(int index) Returns the element at the specified position in this list. E getFirst() Returns the first element in this list. E getLast() Returns the last element in this list.
int indexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
int lastIndexOf(Object o)
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. ListIterator<E> listIterator(int index) Returns a list-iterator of the elements in this list (in proper sequence), starting at the specified position in the list.
boolean offer(E e)
Adds the specified element as the tail (last element) of this list.
38
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Inserts the specified element at the end of this list. E peek() Retrieves, but does not remove, the head (first element) of this list. E peekFirst() Retrieves, but does not remove, the first element of this list, or returns null if this list is empty. E peekLast() Retrieves, but does not remove, the last element of this list, or returns null if this list is empty. E poll() Retrieves and removes the head (first element) of this list E pollFirst() Retrieves and removes the first element of this list, or returns null if this list is empty. E pollLast() Retrieves and removes the last element of this list, or returns null if this list is empty. E pop() Pops an element from the stack represented by this list.
void push(E e)
Pushes an element onto the stack represented by this list. E remove() Retrieves and removes the head (first element) of this list. E remove(int index) Removes the element at the specified position in this list.
boolean
remove(Object o) 39
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework Removes the first occurrence of the specified element from this list, if it is present. E removeFirst() Removes and returns the first element from this list.
boolean removeFirstOccurrence(Object o)
Removes the first occurrence of the specified element in this list (when traversing the list from head to tail). E removeLast() Removes and returns the last element from this list.
boolean removeLastOccurrence(Object o)
Removes the last occurrence of the specified element in this list (when traversing the list from head to tail). E set(int index, E element) Replaces the element at the specified position in this list with the specified element.
int size()
Returns the number of elements in this list. Object[] toArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[] toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
java.util
Class PriorityQueue<E>
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
40
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. A priority queue does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastException). The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily. The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.
A priority queue is unbounded, but has an internal capacity governing the size of an array used to store the elements on the queue. It is always at least as large as the queue size. As elements are added to a priority queue, its capacity grows automatically.
Constructor Summary
PriorityQueue() Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering. PriorityQueue(Collection<? extends E> c) Creates a PriorityQueue containing the elements in the specified collection. PriorityQueue(int initialCapacity) Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering. PriorityQueue(int initialCapacity, Comparator<? super E> comparator) Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator. PriorityQueue(PriorityQueue<? extends E> c) Creates a PriorityQueue containing the elements in the specified priority queue. PriorityQueue(SortedSet<? extends E> c) Creates a PriorityQueue containing the elements in the specified sorted set.
41
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Method Summary
boolean add(E e)
Removes all of the elements from this priority queue. Comparator<? comparator() super E> Returns the comparator used to order the elements in this queue, or null if this queue is sorted according to the natural ordering of its elements.
boolean contains(Object o)
Returns true if this queue contains the specified element. Iterator<E> iterator() Returns an iterator over the elements in this queue.
boolean offer(E e)
Inserts the specified element into this priority queue. E peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. E poll() Retrieves and removes the head of this queue, or returns null if this queue is empty.
boolean remove(Object o)
Removes a single instance of the specified element from this queue, if it is present.
int size()
Returns the number of elements in this collection. Object[] toArray() Returns an array containing all of the elements in this queue.
<T> T[] toArray(T[] a)
Returns an array containing all of the elements in this queue; the runtime type of the 42
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.
Technical Lobby, Raipur (http://www.technicallobby.com/) The Collections Framework returned array is that of the specified array.
43
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified and re-created. Any such misuse will be entertained by Indian Copyright Law.