Java Collection Notes.
Java Collection Notes.
An array is an indexed Collection of fixed number of homogeneous data elements. The Main
advantage of Arrays is we can represent multiple values with a single variable. So that
reusability of the code will be improved.
ii. List :
* List is child interface of Collection.
* If we want to represent a group of individual objects as a single entity where duplicates are
allowed and insertion order preserved then we should go for List.
COLLECTION(I)(V1.2)
LIST(I)
(1.2V)
(V1.0)STACK(CC)
:-SINCE VECTOR ARE AVAILABLE FROM “V1.0” THAT’S WHY WE CALL THEM
LEGACY CLASSES
:These class were reengineered for implementing list Interface
I- INTERFACE
C-CLASS
CC-CHIELD_CLASS
iii. Set:
* It is the child interface of Collection.
* If we want to represent a group of individual objects as a single entity where duplicates are
not allowed and insertion order not preserved then we should go for Set.
COLLECTION(I)
(V1.2)
SET
(V1.2)
HashSet(C) SortedSet(I)(V1.2)
(V1.2)
LinkedHashSet(C) NavigableSet(I)(V1.6)
(V1.4)
TreeSet(C)(V1.2)
iv. SortedSet:
It is the child interface of Set.
If we want to represent a group of individual objects as a single entity where duplicates are
not allowed but all objects should be inserted according to some sorting orde then we should
go for SortedSet.
Set
Duplicates are not allowed
Insertion order not preserved
vi. Queue:
* It is child interface of Collection.
* If we want to represent a group of individual objects prior to processing(eirlier than the
default sequence) then we should go for Queue.
Ex: before sending a mail all mail id's we have to store somewhere and in which order we
saved in the same order mail's should be delivered (First in First out) for this requirement
Queue concept is the best choice.
Note:
* All the above interfaces
(Collection, List, Set, SortedSet, NavigableSet and Queue) meant for representing a group of
individual objects.
* If we want to represent a group of objects as key value pairs then we should go for Map
Interface.
vii. Map:
* Map is not the child interface of Collection.
* If we want to represent a group of individual objects as key value pairs then should go for
Map.
Ex:
Roll No Name
101 Durga
102 Ravi
103 Venkat
Both key and value are objects, duplicated keys are not allowed but values can be duplicated
viii. SortedMap:
* It is the child interface of map.
* If we want to represent a group of key value pairs according to some sorting order of keys
then we should go for SortedMap
ix. NavigableMap:
* It is the child interface of sorted map, it defines several utility methods for navigation
purpose.
x. TreeMap:
TreeMap is a class in the Java Collections Framework that provides an
implementation of the SortedMap interface. It represents a map that is sorted
according to the natural ordering of its keys or by a custom Comparator provided
during its creation.
If we want to represent group of data as a single entity then we should go for Collection.
boolean add(Object o)
boolean addAll(Collection c)
boolean remove(Object o)
boolean removeAll(Collection c)
boolean retainAll(Collection c)
void clear()
boolean contains(Object o)
boolean containsAll(Collection c)
boolean isEmpty()
int size()
object[] toArray()
Iterator iterator()
Note:
Collection interface doesn't contain any method to retrieve objects there is no concrete class
which implements collection class directly.
LIST INTERFACE
* It is the child interface of Collection.
* If we want to represent a group of individual objects as a single entity where duplicates are
allowed and insertion order must be preserved then we should go for List.
* We can differentiate duplicates by using index.
* We can preserve insertion order by using index, hence index play very important role in list
interface.
ArrayList:-
The underlined data structure Resizable Array or Growable Array
Duplicates are allowed.
• Insertion order is preserved.
Heterogeneous objects are allowed [except TreeSet & TreeMap everywhere heterogeneous
objects are allowed].
• Null insertion is possible.
ArrayList Constructors:
1. ArrayList al = new ArrayList()
Creates an empty Array list object with default initial capacity 10. Once Array List reaches its
map capacity a new Array List will be created with new capacity = (currentcapacity * 3/2) + 1.
* Usually we can use Collections to hold and transfer Objects from one place to another place,
to provide support for this requirement every Collection already implements Serializable and
Cloneable interfaces.
*ArrayList and Vector classes implements RandomAccess interface so that we can access any
Random element with the same speed.
* Hence if our frequent operation is retrieval operation then ArrayList is the best choice.
*RandomAccess Interface:
Present in java.util package.
It doesn't contain any methods and it is a Marker interface
*ArrayList is best choice if our frequent operation is retrieval operation (Because ArrayList
implements RandomAccess interfaces)
*ArrayList is the worst choice if our frequent operation is insertion or deletion in the middle
(Because several shift operation are require)
Similarly we can get Synchronized version of Set, Map Objects by using the following
methods of Collections class:
Public static Set synchronizedSet (Set s);
Public static Set synchronizedMap (Map m);
LINKED-LIST
* The underlying data structure is Double Linked List.
* LinkedList is the best choice if our frequent operation is insertion or deletion in the middle.
LinkedList is the worst choice if our frequent operation is retrieval operation.
* Usually we can use LinkedList to implement stacks and queues to provide support for this
requirement LinkedList class defines following specific methods.
void addFirst();
void addLast();
Object getFirst();
Object getLast();
Object removeFirst();
Object removeLast();
LinkedList Constructors
1.LinkedList 11=new LinkedList(); Creates an empty LinkedList Object
VECTOR
* The underlying Data structure for the vector is resizable array or growable array.
* Duplicate objects are allowed.
* Insertion order is preserved.
* 'null' insertion is possible.
* Heterogeneous objects are allowed.
* Vector class implemented Serializable, Cloneable and RandomAccess Interfaces.
* Most of the methods present in Vector are synchronized. Hence Vector object is
Thread-safe.
* Best choice if the frequent operation is retrieval
Constructor of Stack
Stack s=new Stack ();
Methods in Stack
1) Object push(Object obj);
- For inserting an object to the stack
2) Object pop();
- To removes and returns top of the stack.
3) Object peak();
- To Returns the top of the stack without removal of object.
4) int search(Object obj);
- If the specified object is available it returns its offset from top of the stack.
- If the object is not available then it returns -1.
5) Object pop();
- For inserting an object to the stack
EXAMPLE:-
import java.util.*;
class StackDemo {
public static void main (String arg[]) {
Stack s = new Stack ();
s.push ("A");
s.push("B");
s.push ("C");
System.out.println(s); //[A,B,C] System.out.println (s.search ("A")); //[3]
System.out.println (s.search("Z")); //[-1]
}
}
SET
SET
1. Set is the child interface of Collection.
2. If we want to represent a group of individual objects as a single entity, where duplicates are
not allowed and insertion order is not preserved then we should go for Set.
3. Set interface doesn't contain any new methods. So we have to use only Collection interface
methods.
HashSet
*The underlying data structure is Hashtable.
* Duplicates are not allowed. If we are trying to insert duplicates, we won't
get any compiletime or runtime errors. add() method simply returns false.
* Insertion order is not preserved and all objects will be inserted based on hash-code of
objects.
*Heterogeneous objects are allowed.
*'null'insertion is possible.
* implements Serializable and Clonable interfaces but not RandomAccess.
*HashSet is the best choice, if our frequent operation is Search operation.
Constructors of HashSet
import java.util.*;
class HashSetDemo {
public static void main (String[] args) {
HashSet h=new HashSet ();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println (h.add("Z")); // false
System.out.println (h); // [null, D, B, C, 10, Z]
}
}
- Creates an empty HashSet object with default initial capacity 16 & default Fill Retio 0.75
2) HashSet h = new HashSet(int initalCapacity);
- Creates an empty HashSet object with specified initial capacity & default Fill Retio 0.75
3) HashSeth = new HashSet(int initalCapacity, float loadFactor);
- Creates an empty HashSet object with specified initial capacity & specified Load Factor (or
Fill Ratio)
4) HashSet h = new HashSet(Collection c);
import java.util.*;
class LinkedHashSetDemo {
public static void main(String[] args) {
LinkedHashSet h=new LinkedHashSet ();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println (h.add("Z")); // false
System.out.println (h); // [B, C, D, Z, null, 10]
}
}
THE OUTPUT IS IN PRESERVED ORDER
Note:
- LinkedHashSet is the best choice to develop cache based applications, where duplicates are
not allowed and insertion order must be preserved.
SortedSet(I)
1. It is the child interface of set.
2. If we want to represent a group of individual objects according to some sorting order and
duplicates are not allowed then we should go for SortedSet.
SortedSet Specific methods
1.Object first()
- returns first element of the SortedSet
2.Object last()
- returns last element of the SortedSet
3.SortedSet headSet(Object obj) - returns the SortedSet whose elements are <obj
4.SortedSet tallSet(Object obj)
- returns the SortedSet whose elements are >= obj
5.SortedSet subset(Object obj1, Object obj2)
- returns the SortedSet whose elements are >= obj1 and <obj2
6.Comparator comparator()
- returns Comparator object that describes underlying sorting technique. If we are using
default natural sorting order then we will get null.
Example:{100,101,103,104,107,110,115}
1. first():100
2. last():-> 115
3. headset(104) -> [100,101,103]
4. tailSet(104) -> [104,107,110,115]
5. subset(103,110) →> [103,104,107]
6. comparator() → null
Note:
1. Default natural sorting order for numbers Ascending order and for String alphabetical
order.
2. We can apply the above methods only on SortedSet implemented class objects. That is on
the TreeSet object.
NavigableSet
It is the chield interface of SortedSet Interface and It defines several methods for navigation
purposes.
METHODS
1.floor(e) :returns highest element which is e<=Element
2.lower(e):returns highest element which is e<Element
3.ceiling(e):returns lowest element whch is e>=Element
4.higher(e):returns lowest element which is e<Element
5.pollFirst():removes and returns first element
6.pollLast():removes and returns last element
7.descendingSet():reverses the order of the set and returns it.
TreeSet
1. The underlying data structure for TreeSet is Balanced Tree.
2. Duplicate objects are not allowed.
3. Insertion order not preserved, but all objects will be inserted according to some sorting
order.
4. Heterogeneous objects are not allowed. If we are trying to insert heterogeneous objects then
we will get runtime exception saying ClassCastException.
5. Null Insertion is allowed, but only once.
TreeSet Constructors
1. TreeSet t=new TreeSet();
- Creates an empty TreeSet object where elements will be inserted according to default
natural sorting order.
2. TreeSet t-new TreeSet(Comparator c);
- Creates an empty TreeSet Object where elements will be inserted according to customized
sorting order.
3. TreeSet t-new TreeSet(SortedSet s);
4. TreeSet t=new TreeSet(Collection c);
Example:
import java.util.*;
class TreeSetDemo {
public static void main(String[] args) {
TreeSett = new TreeSet();
t.add("A");
Ladd("a");
Ladd("B");
Ladd("Z");
Ladd("L");
// L.add(new Integer(10)); // ClassCastException
L.add(null); // NullPointerException
System.out.println(t); // (A, B, L, Z, a]
}
}
Null Acceptance
1. For empty TreeSet as the first element null insertion is possible. But After inserting that
null if we are trying to insert any another element we will get NullPointerException.
2. For Non empty TreeSet If we are trying to insert Null then we will get
NullPointerExcpetion.
Example
import java.util.TreeSet;
class TreeSetDemo1 {
public static void main(String[] args) {
t.add(new StringBuffer("A"));
TreeSett = new TreeSet();
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("L"));
t.add(new StringBuffer("B"));
System.out.println(t); // ClassCastException}}
Note:
1. If we are depending on default natural sorting order then objects should be homogeneous
and comparable. Otherwise we will get runtime exception saying ClassCastException.
2. An object is said to be comparable if and only if the corresponding class implements
java.lang.comparable interface.
3. String Class and all wrapper classes already implements comparable interface. But
StringBuffer doesn't implement comparable interface.
** Hence in the above program we got ClassCastException **
Comparable Interface
*This interface present in java.lang package it contains only one method CompareTo().
public int CompareTo(Object obj)
Example:
obj1.CompareTo(obj2)
==returns -ve iff obj1 has to come before obj2
==returns +ve iff obj1 has to come after obj2
==returns 0 iff obj1 & obj2 are equal.
Example
class Test {
public static void main(String[] args) {
System.out.println("A".compareTo("Z")); //-ve
System.out.println("Z".compareTo("B")); // +ve
System.out.println("A".compareTo("A")); //0
System.out.println("A".compareTo(null)); // NullPointerException
}
}
Comparator Interface
* We can use comparator to define our own sorting (Customized sorting).
* Comparator interface present in java.util package.
* It defines two methods. compare and equals.
* At line-1 if we are not passing comparator object then internally JVM will call CompareTo()
method which meant for default natural sorting order (ascending order).
In this case output is [0,10,15,20].
*If we are passing comparator object at line 1 then internally JVM will call compare() method
which is meant for customized sorting.
(Descending order). In this case output is [20,15,10,0]
Note:
* If we are defining our own sorting by Comparator, the objects need not be
Comparable.
Note:
1.If we are depending on default natural sorting order then objects should be
homogeneous and comparable otherwise we will get runtime exception saying
ClassCastException.
2.But if we are defining our own sorting by comparator then objects need not be
homogeneous and comparable. we can insert heterogeneous non comparable
objects also.
3) For predefined Comparable classes like String default natural sorting order
already available. If we are not satisfied with that, we can define our own sorting
by Comparator object.
4) For Predefined non comparable classes like StringBuffer, default natural
sorting order is not already available. We can define required sorting by
implementing Comparator interface.
5) For our own classes like Employee, Student, Customer), the person who is
writing our own class, he is responsible to define default natural sorting order by
implementing Comparable interface.
The person who is using our class, if he is not satisfied with default natural
sorting order, then he can define his own sorting by using Comparator.
Demo program for Customized sorting for Employee class: (Page 1 of 3)
import java.util.*;
class Employee implements Comparable {
String name;
int eid;
Employee(String name,int eid){
this.name = name;
this.eid=eid;
}
public String toString() { retum name+"-"+eid;
}
public int compareTo(Object obj) {
int eid1 = this.eid;
Employee e=(Employee)obj; int eid2 = e.eid;
if(eid1<eid2){
return -1;
}else if (eid1>eid2) {
retum 1;
} else {
return 0;
}
}
class CompCompDemo {
public static void main(String[] args) {
Employee e1 = new Employee("nag",100);
Employee e2= new Employee("balalah",200);
Employee e3= new Employee("chiru",50); TreeSet t= new TreeSet(); } }
Employee e4 = new Employee("venkd",150);
Employee e5= new Employee("nag",100)
TreeSet t1=new TreeSet();
t.add(e1);
t.add(e2);
t.add(e3);
t.add(e4);
t.add(e5);
System.out.println(t);
TreeSet t1=new TreeSet(new MyComprator());
t.add(e1);
t1.add(e2);
t1.add(e3);
t1.add(e4);
t1.add(e5);
System.out.println(t);
}
}
Queue interface
1) If we want to represent a group of individual objects prior
(happening before something else) to processing then we should go
for Queue interface.
Collection(1)(1.2)
Queue(1)
PriorityQueue BlockingQueue(1)
PriorityBlockingQueue
LinkedBlockingQueue
List(I) -->LinkedList(C)
2) Usually Queue follows first in first out order but based on our
requirement we can implement our own order also.
PriorityQueue
1) We can use PriorityQueue to represent a group of individual objects
prior to processing
according to some priority.
2) The priority order can be either default natural sorting order (or)
customized sorting
order specified by Comparator object.
3) From 1.5v onwards LinkedList also implements Queue interface.
4) It we are defining our own customized sorting order by Comparator
then the objects need not be homogeneous and Comparable.
5) Duplicate objects are not allowed.
6) Insertion order is not preserved but all objects will be inserted
according to some priority.
7) Null is not allowed even as the 1" element for empty PriorityQueue.
Constructors:
1) PriorityQueue q=new PriorityQueue();
• Creates an empty PriorityQueue with default initial capacity 11 and
default natural sorting order.
2) PriorityQueue q=new PriorityQueue(int initialcapacity, Comparator
c);
3) PriorityQueue q=new PriorityQueue(int initialcapacity);
4) PriorityQueue q=new PriorityQueue(Collection c);
5) PriorityQueue q=new PriorityQueue(SortedSets);
Example 1:
import java.util
class PriorityQueueDemo
public static void main(String[] args)
PriorityQueue q=new PriorityQueued():
//System.out.println(q.peek0)//null
//System.out.println(q.clement());//NoSuchElementException Fortint -
0-10++)
q.offer(i):
System.out.println(q)//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
System.out.println(q.p://0
System.out.println(0)://11, 3, 2, 7,4,5,6, 10, 8, 91
}
}
Note: Some platforms may not provide proper supports for
PriorityQueue windowsXP)
Example 2:
import java.util.":
class PriorityQueueDemo
public static void main(String[] args)
PriorityQueue q=new PriorityQueue(15,new MyComparator}}:
goffer("A":
qoffer(""),
q.offer("L");
qoffer("B"
System.out.println(4).//Z, 8, L. A
class MyComparator implements Comparator{
public int compare(Object obj1, Object obj?){
String s1-(String)obj1;
String s2=obj2.toString();
return s2.compareTo(s1);
}
}
MAP(INTERFACE)
Example:
import java.util.*;
class Map {
public static void main(String[] args) {
HashMap m=new HashMap();
m.put("100","vijay");
System.out.println(m);//{100=vijay}
m.put("100","bhaskar");
System.out.println(m);//{100=bhaskar
}
}
2) void putAll(Map m);
3) Object get(Object key);
4) Object remove(Object key); : It removes the entry associated with specified
key and returns the corresponding value.
5) boolean containsKey(Object key);
6) boolean containsValue(Object value);
7) boolean isEmpty();
8) Int size();
9) void clear();
10) Set keySet(); : The set of keys we are getting.
11) Collection values(); : The set of values we are getting.
12) Set entrySet(); The set of entryset we are getting."
MAP INTERFACE IMPLEMENTING CLASSES
HashMap :-
3) Insertion order is not preserved and it is based on hash code of the keys.
Constructors in HashMap:
1) HashMap m=new HashMap(); :Creates an empty HashMap object with default
initial capacity 16 and default fill ratio “075”.
class HashMapDemo {
m.put("chiranjeevi",700);
m.put("balaiah",800);
m.put("venkatesh",200);
m.put("nagarjuna",500); System.out.println(m);//{nagarjuna=500,
venkatesh=200, balaiah=800, chiranjeevi=700}
System.out.println(m.put("chiranjeevi",100));//700
Set s=m.keySet();
Set s1=m.entrySet();
System.out.println(s1);//[nagarjuna=500, venkatesh=200,
balaiah=800, chiranjeevi=100]
Iterator itr=s1.iterator();
while(itr.hasNext())
Map.Entry m1=(Map.Entry)itr.next();
System.out.println(m1.getKey()+"......"+m1.getValue());//nagarjuna......500
//venkatesh......200 //balaiah......800 //chiranjeevi......100
if(m1.getKey().equals("nagarjuna"))
m1.setValue(1000);
System.out.println(m);//{nagarjuna=1000, venkatesh=200,
balaiah=800, chiranjeevi=100} }"
}}
LinkedHashMap
IdentityHashMap
1) It is exactly same as HashMap except the following differences.
3) But in the case of IdentityHashMap JVM will use== (double equal operator) to
identify duplicate keys."
Example :
class IdHmap{
public static void main(String args[]){
HashMap H=new HashMap();
Integer i=new Integer(10);
Integer ii=new Integer(10);
H.put(i,”Home”);
H.put(ii,”House”);
System.out.println(i==ii);
System.out.println(i.equals(ii));
}
}
WeakHashMap
It is exactly same as HashMap except the following differences.
In the case of normal HashMap, an object is not eligible for GC even though it
doesn’t have any references if it is associated with HashMap. That is HashMap
dominates garbage collector.
But in the case of WeakHashMap if an object does not have any references then
it’s always eligible for GC even though it is associated with WeakHashMap that
is garbage collector dominates WeakHashMap.
Example:
import java.util.*;
class WeakHashMapDemo {
m.put(t,"bhaskar");
System.out.println(m);//{Temp=bhaskar}
t=null;
System.gc();
Thread.sleep(5000);
System.out.println(m);//{} } }
class Temp {
{ return "Temp"; }
Output: {Temp=bhaskar}
Sorting is possible only based on the keys but not based on values.
2) Object lastKey();
6) Comparator comparator();
TreeMap
1) The underlying data structure is RED-BLACK Tree.
3) Insertion order is not preserved and all entries will be inserted according to
some sorting order of keys.
5) If we are defining our own sorting order by Comparator then keys can be
heterogeneous and non Comparable. 377
7) For the empty TreeMap as first entry null key is allowed but after inserting
that entry if we are trying to insert any other entry we will get
NullPointerException.
8) For the non empty TreeMap if we are trying to insert an entry with null key we
will get NullPointerException.
Constructors:
1) TreeMap t=new TreeMap(); For default natural sorting order.
class TreeMapDemo
t.put(100,"ZZZ");
t.put(103,"YYY");
t.put(101,"XXX");
t.put(104,106);
t.put(107,null);
//t.put("FFF","XXX");//ClassCastException
//t.put(null,"xxx");//NullPointerException
Example2:import java.util.*;
class TreeMapDemo
t.put("XXX",10); 378
t.put("AAA",20);
t.put("ZZZ",30);
t.put("LLL",40);
{ String s1=obj1.toString();
2) Insertion order is not preserved and it is based on hash code of the keys.
4) Null key (or) null value is not allowed otherwise we will get
NullPointerException.
Example:
import java.util.*;
class HashtableDemo {
h.put(new Temp(5),"A");
h.put(new Temp(2),"B");
h.put(new Temp(6),"C");
h.put(new Temp(16),"F");
class Temp {
int i;
Temp(int i)
{ this.i=i; }
4) The main advantage in this approach is if there is any change in property files
automatically those changes will be available to java application just
redeployment is enough.
5) By using Properties object we can read and hold properties from property
files into java application.
Constructors
Properties p=new Properties();
3) Enumeration propertyNames();
import java.io.*;
class PropertiesDemo {
System.out.println(p);//{user=scott, password=tiger,
venki=8888}
String s=p.getProperty("venki");
System.out.println(s);//8888
p.setProperty("nag","9999999");
Enumeration e=p.propertyNames();
while(e.hasMoreElements())
String s1=(String)e.nextElement();
System.out.println(s1);//nag //user //password
//venki } FileOutputStream fos=new
FileOutputStream("abc.properties");
Property file