Professional Documents
Culture Documents
Unit 1 Collection Framework
Unit 1 Collection Framework
Collections Interfaces
The Java Collection interface (java.util.Collection) is one of the
root interfaces of the Java Collection API.. Though you do not
instantiate a Collection directly, but rather a subtype of
Collection, you may often treat these subtypes uniformly as a
Collection.
Create a Collection
As just mentioned above, you do not create a Collection instance
directly, but an instance of one of the subtypes of Collection. Here is an
example of creating a List which is a subtype of Collection:
Collection Subtypes
The following interfaces (collection types) extends
the Java Collection interface:
List
Set
SortedSet
NavigableSet
Queue
Deque
Java does not come with a usable implementation of the Collection interface,
so you will have to use one of the listed subtypes. The Collection interface just
defines a set of methods (behaviour) that each of these Collection subtypes
share. This makes it possible ignore what specific type of Collection you are
using, and just treat it as a Collection.
void clear( )
Removes all elements from the invoking collection.
int hashCode( )
boolean isEmpty( )
int size( )
It is possible to specify generic types for most (if not all) of the
components in the Java Collections API.
When you set a generic type for a Java Collection, you do so when you
declare the variable referencing it. Here is an example of setting the generic
type of a Collection and HashSet to a Java String - meaning it can only
contain String instances:
Generic Iterator
When you have specified a generic type for a Java collection, that generic
type also works for the Iterator returned by the iterator() method. Here
is an example of how obtaining an Iterator with a generic type set on it looks:
while(iterator.hasNext()) {
String element = iterator.next();
//do something with element.
}
Notice how it is not necessary to cast the String returned from
the iterator.next() method call. Because the Iterator has its generic
type set to String, the Java compiler already knows that next() will return a
String.
List
You can add any Java object to a List. If the List is not typed, using Java
Generics, then you can even mix objects of different types (classes) in the
same List. Mixing objects of different types in the same List is not often
done in practice, however.
listA.add("element 1");
listA.add("element 2");
listA.add("element 3");
Set Interface
A Set is a Collection that cannot contain duplicate elements.
The Set interface contains only methods inherited from Collection
and adds the restriction that duplicate elements are prohibited.
The Java Set interface, java.util.Set, represents a collection of objects
where each object in the Java Set is unique. In other words, the same object
cannot occur more than once in a Java Set. The Java Set interface is a
standard Java interface, and it is a subtype of the Java Collection interface,
meaning Set inherits from Collection.
You can add any Java object to a Java Set. If the Set is not typed,
using Java Generics, then you can even mix objects of different types
(classes) in the same Set. Mixing objects of different types in the
same Set is not often done in reality, however.
Java Set vs. List
The Java Set and Java List interfaces are quite similar to each other. Bot
interfaces represents a collection of elements. However, there are some
significant differences. These differences are reflected in the methods
the Set and List interfaces contain.
The first difference between the Java Set and List interface is, that the
same element cannot occur more than once in a Java Set. This is different
from a Java List where each element can occur more than once.
The second difference between a Java Set and Java List interfaces is,
that the elements in a Set has no guaranteed internal order. The elements in
a List has an internal order, and the elements can be iterated in that order.
import java.util.HashSet;
setA.add(element);
System.out.println( setA.contains(element) );
}
}
SortedSet Interface
SortedSet Methods
Object first( )
Returns the first element in the invoking sorted set.
Object last( )
Returns the last element in the invoking sorted set.
SortedSet subSet(Object start, Object end)
Returns a SortedSet that includes those elements
between start and end-1. Elements in the returned collection are
also referenced by the invoking object.
SortedSet headSet(Object end)
Returns a SortedSet containing those elements less than
end that are contained in the invoking sorted set.
SortedSet tailSet(Object start)
Returns a SortedSet that contains those elements greater
than or equal to start that are contained in the sorted set.
LinkedList
The LinkedList class extends AbstractSequentialList and
implements the List interface.
Apart from the methods inherited from its parent classes,
LinkedList defines following methods
LinkedList Methods
void addFirst(Object o)
Inserts the given element at the beginning of this list.
void addLast(Object o)
Appends the given element to the end of this list.
Object getFirst()
Returns the first element in this list.
Object getLast()
Returns the last element in this list
Object removeFirst()
Removes and returns the first element from this list.
Object removeLast()
Removes and returns the last element from this list.
LinkedList Example
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
LinkedList ll = new LinkedList();
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll:"+ll);
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion:"+ll);
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last:"+ll);
}}
ArrayList
The ArrayList class extends AbstractList and implements
the List interface. ArrayList supports dynamic arrays that
can grow as needed.
Standard Java arrays are of a fixed length. After arrays are
created, they cannot grow or shrink, which means that you
must know in advance how many elements an array will
hold.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
ArrayList al = new ArrayList();
size of al:"+al.size());
System.out.println("Initial size
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions:"+al.size());
System.out.println("Contents of al: " + al);
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions:"+al.size());
System.out.println("Contents of al: " + al);
}}
Vector
Vector implements a dynamic array. It is similar to
ArrayList, but with two differences:
Vector is synchronized.
Vector contains many legacy methods that are not part of
the collections framework.
Vector Methods
void addElement(Object obj)
Adds the specified component to the end of this vector,
increasing its size by one.
Object firstElement()
Returns the first component (the item at index 0) of this
vector.
Object lastElement()
Returns the last component of the vector.
void setSize(int newSize)
Sets the size of this vector.
Ex:
import java.util.*;
class VectorDemo {
public static void main(String args[]) {
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity:"+v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four
additions:"+v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity:"+v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity:"+v.capacity());
System.out.println("First element:"+v.firstElement());
System.out.println("Last element:"+v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
Enumeration vEnum = v.elements();
System.out.println("\nElements
System.out.println(" nElements in vector:");
while(vEnum.hasMoreElements())
while(vEnum.h
System.out.print(vEnum.nextElement() + " ");
System.out.println(); }}
Stack
Stack Example
import java.util.*;
class stackDemo {
public static void main(String args[]) {
Stack s=new Stack();
s.push(new Integer(10));
s.push(new Integer(20));
s.push(new Integer(30));
System.out.println("Elements:"+s);
System.out.println(s.peek());
System.out.println("Elements:"+s);
println("Elements:"+s);
s.pop();
System.out.println("Elements:"+s);
}}
HashSet
HashSet extends AbstractSet and implements the Set
interface.
HashSet Example
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
HashSet hs = new HashSet();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
} }
HashSet Example
import java.util.*;
ava.util.*;
class HashSetDemo {
public static void main(String args[]) {
HashSet hs = new HashSet();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("A");//duplicate value
System.out.println(hs);
}}
LinkedHashSet
import java.util.*;
class LinkedHashSetDemo
HashSetDemo {
public static void main(String args[]) {
LinkedHashSet hs = new LinkedHashSet();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs); } }
TreeSet
TreeSet Example
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
TreeSet hs = new TreeSet(Collections.reverseOrder());
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}}
Map Interface
The Map interface maps unique keys to values. A key is an
object that you use to retrieve a value at a later date.
Given a key and a value, you can store the value in a Map
object. After the value is stored, you can retrieve it by
using its key.
Map Interface Methods
void clear( )
Removes all key/value pairs from the invoking map.
boolean containsKey(Object k)
Returns true if the invoking map contains k as a key.
Otherwise, returns false.
boolean containsValue(Object v)
Returns true if the map contains v as a value. Otherwise,
returns false.
Object get(Object k)
Returns the value associated with the key k.
boolean isEmpty( )
Returns true if the invoking map is empty. Otherwise,
returns false.
Object put(Object k, Object v)
Puts an entry in the invoking map, overwriting any
previous value associated with the key. The key and value are
k and v, respectively. Returns null if the key did not already
exist. Otherwise, the previous value linked to the key is
returned.
Object remove(Object k)
Removes the entry whose key equals k.
int size( )
Returns the number of key/value pairs in the map.
SortedMap
The SortedMap interface extends Map.
It ensures that the entries are maintained in ascending key
order
SortedMap Methods
Object firstKey( )
Returns the first key in the invoking map.
SortedMap headMap(Object end)
Returns a sorted map for those map entries with keys that
are less than end.
Object lastKey( )
Returns the last key in the invoking map.
SortedMap subMap(Object start, Object end)
Returns a map containing those entries with keys that are
greater than or equal to start and less than end
SortedMap tailMap(Object start)
Returns a map containing those entries with keys that are
greater than or equal to start.
HashMap Example
import java.util.*;
class hashmapdemo{
public static void main(String args[]){
HashMap h=new HashMap();
h.put(1,new String("one"));
h.put(5,new String("five"));
h.put(2,new String("two"));
System.out.println("Elements:"+h);
System.out.println(h.get(5));
h.remove(5);
System.out.println("Elements:"+h);
} }
HashMap Example
import java.util.*;
class hashmapdemo{
public static void main(String args[]){
HashMap h=new HashMap();
h.put(1,new String("one"));
h.put(new String("hello"),new String("five"));
h.put(2,new Stri
String("two"));
h.put(new Character('a'),new String("kkkk"));
h.put(new Character('A'),new String("lll"));
h.put(new Character('b'), new String("jjjj"));
System.out.println("Elements:"+h);
} }
TreeMap Example
import java.util.*;
class hashmapdemo{
public static void main(String args[]){
TreeMap t=new TreeMap();
t.put(1,new String("one"));
t.put(5,new String("five"));
t.put(2,new String("two"));
System.out.println("Elements:"+t);
System.out.println("Ele
}}
TreeMap Example
import java.util.*;
class hashmapdemo{
public static void main(String args[]){
TreeMap t=new TreeMap();
t.put(new Character('B'),new Integer(10));
t.put(new Character('C'),new Intege
Integer(20));
r(20));
t.put(new Character('A'),new Integer(30));
System.out.println("Elements:"+t);
}}
Queue Interface
The interface Queue is available in the java.util package and does extend
the Collection interface. It is used to keep the elements that are processed
in the First In First Out (FIFO) manner. It is an ordered list of objects, where
insertion of elements occurs at the end of the list, and removal of elements
occur at the beginning of the list.
Method Description
boolean It is used to insert the specified element into this queue and return true upon
add(object) success.
Object remove() It is used to retrieves and removes the head of this queue.
Object poll() It is used to retrieves and removes the head of this queue, or returns null if this
queue is empty.
Object element() It is used to retrieves, but does not remove, the head of this queue.
Object peek() It is used to retrieves, but does not remove, the head of this queue, or returns
null if this queue is empty.
PriorityQueue :
[]
[10, 20, 30]
10
[10, 20, 30]
10
[20, 30]
20
[30]
Deque Interface
The interface called Deque is present in java.util package. It is the subtype of the
interface queue. The Deque supports the addition as well as the removal of elements
from both ends of the data structure. Therefore, a deque can be used as a stack or a
queue. We know that the stack supports the Last In First Out (LIFO) operation, and the
operation First In First Out is supported by a queue. As a deque supports both, either of
the mentioned operations can be performed on it. Deque is an acronym for "double
ended queue".
boolean It is used to insert the specified element into this deque and return true upon success.
add(object)
Object remove() It is used to retrieve and removes the head of this deque.
Object poll() It is used to retrieve and removes the head of this deque, or returns null if this deque is
empty.
Object element() It is used to retrieve, but does not remove, the head of this deque.
Object peek() It is used to retrieve, but does not remove, the head of this deque, or returns null if this
deque is empty.
Object The method returns the head element of the deque. The method does not remove any
peekFirst() element from the deque. Null is returned by this method, when the deque is empty.
Object The method returns the last element of the deque. The method does not remove any
peekLast() element from the deque. Null is returned by this method, when the deque is empty.
Boolean Inserts the element e at the front of the queue. If the insertion is successful, true is returned;
offerFirst(e) otherwise, false.
Object Inserts the element e at the tail of the queue. If the insertion is successful, true is returned;
offerLast(e) otherwise, false.
ArrayDeque class
We know that it is not possible to create an object of an interface in Java. Therefore, for
instantiation, we need a class that implements the Deque interface, and that class is
ArrayDeque. It grows and shrinks as per usage. It also inherits the AbstractCollection
class.
1. import java.util.*;
2. public class ArrayDequeExample {
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Ravi");
7. deque.add("Vijay");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }
1. import java.util.*;
2. public class DequeExample {
3. public static void main(String[] args) {
4. Deque<String> deque=new ArrayDeque<String>();
5. deque.offer("arvind");
6. deque.offer("vimal");
7. deque.add("mukul");
8. deque.offerFirst("jai");
9. System.out.println("After offerFirst Traversal...");
10. for(String s:deque){
11. System.out.println(s);
12. }
13. //deque.poll();
14. //deque.pollFirst();//it is same as poll()
15. deque.pollLast();
16. System.out.println("After pollLast() Traversal...");
17. for(String s:deque){
18. System.out.println(s);
19. }
20. }
21. }
Comparator Interface
A comparator interface is used to order the objects of user-defined classes. A comparator
object is capable of comparing two objects of the same class.
Syntax:
public int compare(Object obj1, Object obj2)
// Class 1
// A class to represent a Student
class Student {
// Attributes of a student
int rollno;
String name, address;
// Constructor
public Student(int rollno, String name, String address)
{
// Class 2
// Helper class implementing Comparator interface
class Sortbyroll implements Comparator<Student> {
// Method
// Sorting in ascending order of roll number
public int compare(Student a, Student b)
{
// Class 3
// Helper class implementing Comparator interface
class Sortbyname implements Comparator<Student> {
// Method
// Sorting in ascending order of name
public int compare(Student a, Student b)
{
return a.name.compareTo(b.name);
}
}
// Class 4
// Main class
class GFG {
Example:
import java.util.*;
public class AlgorithmsDemo {
// Get iterator
Iterator li = ll.iterator();
System.out.print("List sorted in reverse: ");
while(li.hasNext()) {
System.out.print(li.next() + " ");
}
System.out.println();
Collections.shuffle(ll);
while(li.hasNext()) {
System.out.print(li.next() + " ");
}
System.out.println();
System.out.println("Minimum: " + Collections.min(ll));
System.out.println("Maximum: " + Collections.max(ll));
}
}
Output
List sorted in reverse: 20 8 -8 -20
List shuffled: 20 -20 8 -8
Minimum: -20
Maximum: 20
Arrays class
The Arrays class in java.util package is a part of the Java Collection Framework. This
class provides static methods to dynamically create and access Java arrays. It consists
of only static methods and the methods of Object class. The methods of this class can be
used by the class name itself.
deepEquals(Object[] a1, Object[] Returns true if the two specified arrays are
a2) deeply equal to one another.
parallelPrefix(originalArray,
fromIndex, endIndex, Performs parallelPrefix for the given range of
functionalOperator) the array with the specified functional operator.
sort(T[] a, int fromIndex, int Sorts the specified range of the specified array
toIndex, Comparator< super T> of objects according to the order induced by the
c) specified comparator.
import java.util.Arrays;
// Main class
class Demo {
public static void main(String[] args)
{
// Get the Array
int intArr[] = { 10, 20, 15, 22, 35 };
System.out.println("Integer Array as List: "
+ Arrays.asList(intArr));
}
}
Legacy Classes
Early version of java did not include the Collections framework. It only defined
several classes and interfaces that provide methods for storing objects. When
Collections framework was added in J2SE 1.2, the original classes were
reengineered to support the collection interface. These classes are also known
as Legacy classes. All legacy classes and interface were redesign by JDK 5 to
support Generics. In general, the legacy classes are supported because there is
still some code that uses them.
1. Dictionary
2. HashTable
3. Properties
4. Stack
5. Vector
There is only one legacy interface called Enumeration
Enumeration interface
Vector class
1. Vector is similar to ArrayList which represents a dynamic array.
2. There are two differences between Vector and ArrayList. First, Vector is
synchronized while ArrayList is not, and Second, it contains many legacy
methods that are not part of the Collections Framework.
3. With the release of JDK 5, Vector also implements Iterable. This means
that Vector is fully compatible with collections, and a Vector can have its
contents iterated by the for-each loop.
Vector defines several legacy methods. Lets see some important legacy
methods defined by Vector class.
Method Description
void addElement(E element) adds element to the Vector
Example of Vector
import java.util.*;
ve.add(10);
ve.add(20);
ve.add(30);
ve.add(40);
ve.add(50);
ve.add(60);
Enumeration<Integer> en = ve.elements();
while(en.hasMoreElements())
System.out.println(en.nextElement());
10
20
30
40
50
60
Hashtable class
1. Like HashMap, Hashtable also stores key/value pair. However
neither keys nor values can be null.
import java.util.*;
class HashTableDemo
Hashtable<String,Integer> ht = new
Hashtable<String,Integer>();
ht.put("a",new Integer(100));
ht.put("b",new Integer(200));
ht.put("c",new Integer(300));
ht.put("d",new Integer(400));
Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
Map.Entry m=(Map.Entry)itr.next();
System.out.println(m.getKey()+" "+m.getValue());
}
a 100
b 200
c 300
d 400
Hashtable HashMap
Neither key nor values can be null Both key and values can be null
Properties class
1. Properties class extends Hashtable class.
2. It is used to maintain list of value in which both key and value are String
3. Properties class define two constructor
import java.util.*;
{
Properties pr = new Properties();
Stack class
4. If you want to put an object on the top of the stack, call push() method.
If you want to remove and return the top element, call pop() method. An
EmptyStackException is thrown if you call pop() method when the
invoking stack is empty.
You can use peek() method to return, but not remove, the top object. The
empty() method returns true if nothing is on the stack. The search() method
determines whether an object exists on the stack and returns the number of
pops that are required to bring it to the top of the stack.
Example of Stack
import java.util.*;
class StackDemo {
st.push(11);
st.push(22);
st.push(33);
st.push(44);
st.push(55);
Enumeration e1 = st.elements();
while(e1.hasMoreElements())
System.out.print(e1.nextElement()+" ");
st.pop();
st.pop();
Enumeration e2 = st.elements();
while(e2.hasMoreElements())
System.out.print(e2.nextElement()+" ");
11 22 33 44 55
11 22 33
Dictionary class
1. Dictionary is an abstract class.
After Generics:
LinkedList<Integer> l=new LinkedList<Integer>();
l.add(new Integer(30));
Integer i=l.get(0);
class one<F,S>{
F first;
S second;
one(F f,S s){
first= f; second=s;
}
}
class two<F,S,T> extends one<F,S>{
T third;
two(F f,S s,T t){
super(f,s);
third=t;
}
void show(){
System.out.println("First value:"+first);
System.out.println("First value:"+second);
System.out.println("First value:"+third);
}
}
public class demo {