Core Java - Java Collections Framework Tutorial (Chapter 14)

55
Technical Lobby, Raipur (http://www.technicallobby.com/ ) The Collections Framework 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). What Is a Collections Framework? A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following: Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy. Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures. Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality. 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. 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.

description

This documents helps in understanding the Java Collection Framework. If you like this document then please visit our site http://www.technicallobby.com/ and leave a comment. This document is part of Technical Lobby's study material archive. Enjoy reading!

Transcript of Core Java - Java Collections Framework Tutorial (Chapter 14)

Page 1: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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

What Is a Collections Framework?A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following: Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy. Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures. Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.

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 core collection interfaces.

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

1This 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.

Page 2: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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

Collection — 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.

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:

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.

The Collection Interface2

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.

Page 3: Core Java - Java Collections Framework Tutorial (Chapter 14)

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 CollectionsThere are two ways to traverse collections: (1) with the for-each construct and (2) by using Iterators.

3This 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.

Page 4: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

for-each ConstructThe 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);

IteratorsAn 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:

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.

The following method shows you how to use an Iterator to filter an arbitrary Collection — that is, 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

4This 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.

Page 5: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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:

containsAll — returns true if the target Collection contains all of the elements in the specified Collection.

addAll — adds all of the elements in the specified Collection to the target Collection. removeAll — removes from the target Collection all of its elements that are also contained in the

specified Collection. retainAll — removes from the target Collection all its elements that are not also contained in

the specified Collection. That is, it retains only those elements in the target Collection that are also contained in the specified Collection.

clear — removes all elements from the Collection.

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 containing only the specified element.

Collection Interface Array OperationsThe 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 Set Interface

5This 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.

Page 6: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements.

The following is the Set interface.

public interface Set<E> extends Collection<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 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 no guarantees concerning the order of iteration.

TreeSet, which stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet.

LinkedHashSet, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order).

The List InterfaceA List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for the following:

Positional access — manipulates elements based on their numerical position in the list Search — searches for a specified object in the list and returns its numerical position

6This 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.

Page 7: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

Iteration — extends Iterator semantics to take advantage of the list's sequential nature Range-view — performs arbitrary range operations on the list.

The List interface follows.

public interface List<E> extends Collection<E> { // Positional access E get(int index); E set(int index, E element); //optional boolean add(E element); //optional void add(int index, E element); //optional E remove(int index); //optional boolean addAll(int index, Collection<? extends E> c); //optional

// Search int indexOf(Object o); int lastIndexOf(Object o);

// Iteration ListIterator<E> listIterator(); ListIterator<E> listIterator(int index);

// Range-view List<E> subList(int from, int to);}

The Queue InterfaceA Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations. The Queue interface follows. public interface Queue<E> extends Collection<E> { E element(); boolean offer(E e); E peek(); E poll(); E remove();}

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.

7This 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.

Page 8: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

The Map InterfaceA Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction. The Map interface follows. public interface Map<K,V> {

// Basic operations V put(K key, V value); V get(Object key); V remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty();

// Bulk operations void putAll(Map<? extends K, ? extends V> m); void clear();

// Collection Views public Set<K> keySet(); public Collection<V> values(); public Set<Map.Entry<K,V>> entrySet();

// Interface for entrySet elements public interface Entry { K getKey(); V getValue(); V setValue(V value); }}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 OrderingA 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 Natural Ordering

8This 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.

Page 9: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

Byte Signed numerical

Character Unsigned numerical

Long Signed numerical

Integer Signed numerical

Short Signed numerical

Double Signed numerical

Float Signed numerical

BigInteger Signed numerical

BigDecimal Signed numerical

Boolean Boolean.FALSE < Boolean.TRUE

File System-dependent lexicographic on path name

String Lexicographic

Date Chronological

CollationKey Locale-specific lexicographic

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 TypesThe Comparable interface consists of the following method.

public interface Comparable<T> { public int compareTo(T o);}

9This 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.

Page 10: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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 than the specified object. If the specified object cannot be compared to the receiving object, the method throws a ClassCastException.

The following class representing a person's name implements Comparable.

import java.util.*;

public class Name implements Comparable<Name> { private final String firstName, lastName;

public Name(String firstName, String lastName) { if (firstName == null || lastName == null) throw new NullPointerException();

this.firstName = firstName; this.lastName = lastName; }

public String firstName() { return firstName; } public String lastName() { return lastName; }

public boolean equals(Object o) { if (!(o instanceof Name)) return false; Name n = (Name)o; return n.firstName.equals(firstName) && n.lastName.equals(lastName); }

public int hashCode() { return 31*firstName.hashCode() + lastName.hashCode(); }

public String toString() {return firstName + " " + lastName;

}

public int compareTo(Name n) { int lastCmp = lastName.compareTo(n.lastName); return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName)); }}See example: ComparableDemo.java

ComparatorsWhat 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

10This 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.

Page 11: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

Comparator — an object that encapsulates an ordering. Like the Comparable interface, the Comparator interface consists of a single method.

public interface Comparator<T> { int compare(T o1, T o2);}The compare method compares its two arguments, returning a negative integer, 0, or a positive integer 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); }}See example: ComparatorsDemo

11This 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.

Page 12: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

The SortedSet InterfaceA SortedSet is a Set that maintains its elements in ascending order, sorted according to the elements' natural ordering or according to a Comparator provided at SortedSet creation time.

The SortedMap InterfaceA SortedMap is a Map that maintains its entries in ascending order, sorted according to the keys' natural ordering, or according to a Comparator provided at the time of the SortedMap creation.

Interface NavigableSetA 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

12This 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.

Page 13: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

if there is no such element.

 Iterator<E> iterator() Returns an iterator over the elements in this set, in ascending order.

 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:

13This 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.

Page 14: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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.

java.util Interface Collection<E>public interface Collection<E>extends Iterable<E>

The root interface in the collection hierarchy.

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

14This 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.

Page 15: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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

 boolean removeAll(Collection<?> c) 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 Objectimplements 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>

15This 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.

Page 16: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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>implements List<E>

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() Removes all of the elements from this list (optional operation).

 boolean equals(Object o) Compares the specified object with this list for equality.

abstract  E 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 of the first occurrence of the specified element in this list, or -1 if

16This 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.

Page 17: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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

removeRange(int fromIndex, int toIndex) 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>

This class provides skeletal implementations of some Queue operations.

17This 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.

Page 18: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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 IllegalStateException if no space is currently available.

 boolean addAll(Collection<? extends E> c) Adds all of the elements in the specified collection to this queue.

 void clear() 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.

java.util Interface Deque<E>public interface Deque<E>extends Queue<E>

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.

18This 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.

Page 19: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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

19This 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.

Page 20: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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.

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

20This 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.

Page 21: Core Java - Java Collections Framework Tutorial (Chapter 14)

Set hierarchy

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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() 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() Returns the number of elements in this deque.

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.

21This 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.

Queue hierarchy

Page 22: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

java.util Class HashSet<E>public class HashSet<E>extends AbstractSet<E>implements Set<E>, Cloneable, Serializable

22This 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.

Page 23: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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.

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.

See example - HashSetDemo.java

java.util Class TreeSet<E>public class TreeSet<E>

23This 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 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.

Page 24: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

extends AbstractSet<E>implements NavigableSet<E>, Cloneable, Serializable

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 the specified element to this set if it is not already present.

 boolean addAll(Collection<? extends E> c) 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

24This 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.

Page 25: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

null if there is no such element.

 void clear() Removes all of the elements from this set.

 Object clone() Returns a shallow copy of this TreeSet instance.

 Comparator<? super E>

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

25This 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.

Page 26: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

if there is no such element.

 boolean isEmpty() Returns true if this set contains no elements.

 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) Removes the specified element from this set if it is present.

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

26This 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.

Page 27: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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.

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

27This 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.

Page 28: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

 

Methods inherited from class java.util.HashSet

add, clear, clone, contains, isEmpty, iterator, remove, size

 

Methods inherited from class java.util.AbstractSet

equals, hashCode, removeAll

 

Methods inherited from class java.util.AbstractCollection

addAll, containsAll, retainAll, toArray, toArray, toString

 

Methods inherited from class java.lang.Object

finalize, getClass, notify, notifyAll, wait, wait, wait

 

Methods inherited from interface java.util.Set

add, addAll, clear, contains, containsAll, equals, hashCode, isEmpty, iterator, remove, removeAll, retainAll, size, toArray, toArray

See example - LinkedHashSetDemo.java

java.util Class ArrayList<E>public class ArrayList<E>extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, Serializable

28This 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.

Page 29: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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.

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 the specified element to the end of this list.

 void add(int index, E element) Inserts the specified element at the specified position in this list.

 boolean addAll(Collection<? extends E> 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.

 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.

29This 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.

Page 30: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

 Object clone() Returns a shallow copy of this ArrayList instance.

 boolean contains(Object o) 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 true if this list contains no elements.

 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.

 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 void

removeRange(int fromIndex, int toIndex) 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()

30This 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.

Page 31: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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.

 void trimToSize() Trims the capacity of this ArrayList instance to be the list's current size.

See example - ArrayListDemo.java

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

31This 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.

Page 32: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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 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 the specified element to the end of this Vector.

 void add(int index, E element) Inserts the specified element at the specified position in this Vector.

 boolean addAll(Collection<? extends E> c) 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() Returns the current capacity of this vector.

 void clear() Removes all of the elements from this Vector.

 Object clone() Returns a clone of this vector.

32This 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.

Page 33: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

 boolean contains(Object o) Returns true if this vector contains the specified element.

 boolean containsAll(Collection<?> c) Returns true if this Vector contains all of the elements in the specified Collection.

 void copyInto(Object[] anArray) 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 hash code value for this Vector.

 int indexOf(Object o) 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.

33This 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.

Page 34: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

 void insertElementAt(E obj, int index) Inserts the specified object as a component in this vector at the specified index.

 boolean isEmpty() Tests if this vector has no components.

 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) Deletes the component at the specified index.

protected void

removeRange(int fromIndex, int toIndex) Removes from this List all of the elements whose index is between fromIndex,

34This 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.

Page 35: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

inclusive and toIndex, exclusive.

 boolean retainAll(Collection<?> c) Retains only the elements in this Vector that are contained in the specified Collection.

 E set(int index, E element) 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) Sets the size of this vector.

 int size() 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() Trims the capacity of this vector to be the vector's current size.

See example - VectorDemo.java

35This 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.

Page 36: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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, 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) Returns the 1-based position where an object is on this stack.

See example - StackDemo.java

36This 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.

Page 37: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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 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 the specified element to the end of this list.

 void add(int index, E element) Inserts the specified element at the specified position in this list.

 boolean addAll(Collection<? extends E> 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.

 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)

37This 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.

Page 38: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

Inserts the specified element at the beginning of this list.

 void addLast(E e) Appends the specified element to the end of this list.

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

38This 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.

Page 39: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

specified position in the list.

 boolean offer(E e) Adds the specified element as the tail (last element) of this list.

 boolean offerFirst(E e) Inserts the specified element at the front of this list.

 boolean offerLast(E e) 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()

39This 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.

Page 40: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

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

See example - LinkedListDemo.java

40This 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.

Page 41: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

java.util Class PriorityQueue<E>public class PriorityQueue<E>extends AbstractQueue<E>implements Serializable

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.

41This 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.

Page 42: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

PriorityQueue(SortedSet<? extends E> c) Creates a PriorityQueue containing the elements in the specified sorted set.

 

Method Summary

 boolean add(E e) Inserts the specified element into this priority queue.

 void clear() Removes all of the elements from this priority queue.

 Comparator<? super E>

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

42This 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.

Page 43: Core Java - Java Collections Framework Tutorial (Chapter 14)

Technical Lobby, Raipur (http://www.technicallobby.com/)

The Collections Framework

 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 returned array is that of the specified array.

See example - PriorityQueueDemo.java

43This 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.