Java Unit-4
Java Unit-4
Java Collections
Collections Overview
The Java Collections Framework standardizes the way in which groups of objects are handled
by your programs.
The Collections Framework was designed to meet several goals.
First, the framework had to be high-performance. The implementations for the fundamental
collections (dynamic arrays, linked lists, trees, and hash tables) are highly efficient.
Second, the framework had to allow different types of collections to work in a similar manner
and with a high degree of interoperability.
Third, extending and/or adapting a collection had to be easy. Toward this end, the entire
Collections Framework is built upon a set of standard interfaces.
Algorithms are another important part of the collection mechanism. Algorithms operate on
collections and are defined as static methods within the Collections class. Thus, they are
available for all collections. Each collection class need not implement its own versions. The
algorithms provide a standard means of manipulating collections.
Another item closely associated with the Collections Framework is the Iterator interface. An
iterator offers a general-purpose, standardized way of accessing the elements within a
collection, one at a time. Thus, an iterator provides a means of enumerating the contents of a
collection. Because each collection implements Iterator, the elements of any collection class
can be accessed through the methods defined by Iterator. Thus, with only small changes, the
code that cycles through a set can also be used to cycle through a list, for example. Iterator
interface provides the facility of iterating the elements in forward direction only. There are only Collection Interfaces:
three methods in the Iterator interface. They are:
1. public boolean hasNext() it returns true if iterator has more elements. The Collection interface:
2. public object next() it returns the element and moves the cursor pointer to the next The Collection interface is the foundation upon which the collections framework is built. It
element. declares the core methods that all collections will have. These methods are summarized in the
3. public void remove() it removes the last elements returned by the iterator. It is rarely following.
used.
Hierarchy of Collection Framework boolean add(Object obj)
Let us see the hierarchy of collection framework. The java.util package contains all the classes Adds obj to the invoking collection. Returns true if obj was added to the collection. Returns
and interfaces for Collection framework. false if obj is already a member of the collection, or if the collection does not allow duplicates.
boolean addAll(Collection c)
Adds all the elements of c to the invoking collection. Returns true if the operation succeeded
(i.e., the elements were added). Otherwise, returns false.
Iterator iterator( )
Returns an iterator for the invoking collection.
boolean remove(Object obj)
Removes one instance of obj from the invoking collection. Returns true if the element was List subList(int start, int end)
removed. Otherwise, returns false. Returns a list that includes elements from start to end.1 in the invoking list. Elements in the
returned list are also referenced by the invoking object.
boolean removeAll(Collection c)
Removes all elements of c from the invoking collection. Returns true if the collection changed Set Interface:
(i.e., elements were removed). Otherwise, returns false. A Set is a Collection that cannot contain duplicate elements. It models the mathematical set
abstraction.
int size( ) The Set interface contains only methods inherited from Collection and adds the restriction
Returns the number of elements held in the invoking collection. that duplicate elements are prohibited.
add( )
Object[ ] toArray( ) Adds an object to the collection
Returns an array that contains all the elements stored in the invoking collection. The array
elements are copies of the collection elements. clear( )
The List interface: Removes all objects from the collection
The List interface extends Collection and declares the behavior of a collection that stores a
sequence of elements. contains( )
Elements can be inserted or accessed by their position in the list, using a zero-based Returns true if a specified object is an element within the collection
index.
A list may contain duplicate elements. remove( )
In addition to the methods defined by Collection, List defines some of its own, which Removes a specified object from the collection
are summarized in the following below Table. Example:
Several of the list methods will throw an UnsupportedOperationException if the Set have its implementation in various classes like HashSet, TreeSet, LinkedHashSet.
collection cannot be modified, and a ClassCastException is generated when one Following is the example to explain Set functionality:
object is incompatible with another.
Object get(int index) import java.util.*;
public class SetDemo {
Returns the object stored at the specified index within the invoking collection. public static void main(String args[]) {
int count[] = {34, 22,10,60,30,22};
int indexOf(Object obj) Set<Integer> set = new HashSet<Integer>();
Returns the index of the first instance of obj in the invoking list. If obj is not an element of the try{
for(int i = 0; i<5; i++){
list, .1 is returned.
set.add(count[i]);
}
int lastIndexOf(Object obj) System.out.println(set);
Returns the index of the last instance of obj in the invoking list. If obj is not an element of the TreeSet sortedSet = new TreeSet<Integer>(set);
list, .1 is returned. System.out.println("The sorted list is:");
System.out.println(sortedSet);
System.out.println("The First element of the set is: "+
ListIterator listIterator( ) (Integer)sortedSet.first());
Returns an iterator to the start of the invoking list. System.out.println("The last element of the set is: "+
(Integer)sortedSet.last());
}
ListIterator listIterator(int index)
catch(Exception e){}
Returns an iterator to the invoking list that begins at the specified index. }
}
Object set(int index, Object obj)
Assigns obj to the location specified by index within the invoking list. The Map interface:
The Map interface maps unique keys to values. A key is an object that you use to retrieve a Returns a collection containing the values in the map. This method provides a collection-view
value at a later date. of the values in the map.
Given a key and a value, you can store the value in a Map object. After the value is Example:
stored, you can retrieve it by using its key.
Several methods throw a NoSuchElementException when no items exist in the import java.util.*;
invoking map. public class CollectionsDemo {
A ClassCastException is thrown when an object is incompatible with the elements in a public static void main(String[] args) {
map. Map m1 = new HashMap();
A NullPointerException is thrown if an attempt is made to use a null object and null is m1.put("Zara", "8");
not allowed in the map. m1.put("Mahnaz", "31");
void clear( ) m1.put("Ayan", "12");
Removes all key/value pairs from the invoking map. m1.put("Daisy", "14");
System.out.println();
boolean containsKey(Object k) System.out.println(" Map Elements");
Returns true if the invoking map contains k as a key. Otherwise, returns false. System.out.print("\t" + m1);
}
boolean containsValue(Object v) }
Returns true if the map contains v as a value. Otherwise, returns false
Set keySet( )
Returns a Set that contains the keys in the invoking map. This method provides a set-view of
the keys in the invoking map.
Stack:
Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only
defines the default constructor, which creates an empty stack.
class Stack<E>
Here, E specifies the type of element stored in the stack.
import java.util.*;
class StackDemo {
static void showpush(Stack<Integer> st, int a) {
st.push(a);
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack<Integer> st) {