Collections Framework
• Collection represents a group of objects, known as its elements
• Group of classes and interface.
• Can store objects in collection classes.
• (lowercase c) collection framework represents any of the data structures in
which objects are stored & retrieved.
• (Uppercase C ends with s) Collections – java.util.Collections class – holds
static utility methods.
• (Uppercase C) Collection is an Interface set the standard for Collection
classes so that they will have uniform method names.
• The five legacy classes: Vector, HashTable, Properties, Directory, Stack
and one legacy interface: Enumeration
• There are some problems with the above legacy classes. In order to avoid
those problems, SUN has introduced Collection framework in Java 2.
• Three categories:
• List - Collection of object with duplicate
• Set - Collection of object without duplicate
• Map - Collection of key / value pairs
Collections
- The java.util package contains one of Java’s most powerful subsystems: collections.
Collections were added by the initial release of Java 2, and enhanced by Java
2,version 1.4. A collection is a group of objects
- In addition to collections, java.util contains a wide assortment of classes and
interfaces that support a broad range of functionality.
- 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.
i. The framework had to be high-performance. The implementations for the
fundamental collections (dynamic arrays, linked lists, trees, and hash tables) are
highly efficient.
ii. The framework had to allow different types of collections to work in a similar
manner and with a high degree of interoperability.
iii. Extending and/or adapting a collection had to be easy.
Collection Interfaces
The collections framework defines several interfaces. Beginning with the collection
interfaces is necessary because they determine the fundamental nature of the
collection classes
But there are sub flavors within those three types:
Ordered
- When a collection is ordered, it means you can iterate through the collection in a
specific (not-random) order.
- A Hashtable collection is not ordered. Although the Hashtable itself has internal logic
to determine the order (based on hashcodes and the implementation of the collection
itself), you won’t find any order when you iterate through the Hashtable.
- An ArrayList, however, keeps the order established by the elements’ index position
(just like an array).
- LinkedHashSet keeps the order established by insertion, so the last element inserted
is the last element in the LinkedHashSet (as opposed to an ArrayList where you can
insert an element at a specific index position).
Sorted
- For a collection of String objects, then, the natural order is alphabetical.
- For Integer objects, the natural order is by numeric value.
- A sorted collection means a collection sorted by natural order.
- And natural order is defined by the class of the objects being sorted
Methods of Collection Interface
List Interface
The List interface extends Collection and declares the behavior of a collection that
stores a sequence of elements. Elements can be inserted or accessed by their position
in the list, using a zero-based index. A list may contain duplicate elements.
The three List implementations are described in the following section.
• (Insertion Order, Elements are stored by index, Duplicates are allowed, Null element is
allowed)
ArrayList
ArrayList supports dynamic arrays that can grow as needed. In Java, standard 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. But, sometimes,
you may not know until run time precisely how large of an array you need. To handle this
situation, the collections framework defines ArrayList.
Creation of Arraylist:
ArrayList name_of_the _arraylist=new ArrayList();
Eg:
ArrayList al=new ArrayList();
Array ArrayList
Size of an array is fixed because, you
need to provide the size when creating
an array
Size of an ArrayList is growable, So no
need to specify size
When array of size ‘n’ with m
elements, then repeat For loop n times
to access m elements, so that (n-m)
times loop will be repeated
unnecessarily.
Using Iterator, we can access only the
available elements, So no waste of
time.
Exception is possible in case m > n No Exception problem
Retrieval is faster.
Array ArrayList
Object o[ ] = new Object[10]; ArrayList al = new ArrayList();
o[0] = new String(“hello”); al.add(new String("Srinivas"));
o[1] = new Integer(99); al.add(new Student(99))
o[2] = new Student[10, “var”]; al.add(new Student(or ,”99”))
for (i = 0; I < o.length; i++)
{
System.out.println(o[i]);
}
Iterator i = al.iterator();
while (i.hasNext())
{
System.out.println(i.next());
}
• import java.util.*;
• class ArrList1 {
• public static void main (String args[])
• {
• ArrayList al = new ArrayList();
• al.add("A");
• al.add("B");
• al.add("d");
• System.out.println("al " +al);
• al.add("C");
• al.set(0, "AA");
• al.add(1, "9");
• System.out.println("al " +al);
• // boolean b = al.contains("C");
• // System.out.println("al contains c " +b);
• System.out.println("al contains C " +al.contains("C"));
• // al.clear();
• // al.get(2);
• System.out.println("al 2 " +al.get(2));
• al.set(0,"1");
• System.out.println("al " +al);
• ArrayList s = (ArrayList) al.clone();
• System.out.println("al clone " +s);
• /*// al.remove("B");
• System.out.println("al removes " +al.remove("B"));
• System.out.println("al " +al);
• System.out.println("al removes " +al.remove("B"));
• System.out.println("al " +al);
• /*al.add (2, "B");
• System.out.println("al added" +al);
• ArrayList al1 = new ArrayList();
• al1.add("1");al1.add("2");al1.add("3");
• System.out.println(al == al1);
• System.out.println(al.equals(al1));
• al.add(al1);System.out.println("al with al1 " +al);
• System.out.println("al size " +al.size());
• al.remove("C");
• System.out.println("al removes C then " +al);
• System.out.println("al " + al.contains("al1"));
• al.removeAll(al1);
• System.out.println("al after " +al);
• al.addAll(al1);
• System.out.println("al after add all" +al);
• al.retainAll(al1);
• import java.util.*;
• public class ArrayListTest2 {
• public static void main(String[] args) {
• ArrayList al = new ArrayList(); al.add(new
Integer(99));System.out.println(al);al.add("Srinivas");al.add("hari@hari.com");
• System.out.println(al); System.out.println(al.size()); System.out.println(al.isEmpty());
• // using toArray() method
• System.out.println("using toArray()");
• int len= al.size();
• Object[] o = new Object[len];
• o = al.toArray();
• for (int i = 0; i < o.length; i++) {
• System.out.println(o[i]);
• }
• // using Iterators
• System.out.println("using Iterators ");
• Iterator iter = al.iterator();
• while(iter.hasNext()){
• System.out.println(iter.next());
• }
• // using ListIterator
• System.out.println("using ListIterator");
• ListIterator liter = al.listIterator();
• while (liter.hasNext())
• {System.out.println(liter.next());}
• System.out.println("Using Previous(Print in reverse order)");
• while(liter.hasPrevious())
• {System.out.println(liter.previous());}
• // using ListIterator SET method Assigns obj to the current element
• System.out.println("using ListIterator");
• ListIterator liter = al.listIterator();
• while (liter.hasNext())
• {
• Object element = liter.next();
• liter.set(element + "+");
• }
• System.out.println("Modified contents" );
• Iterator it1 = al.iterator();
• while(it1.hasNext()) {
• Object element = it1.next();
• System.out.println(element+ "");
• }
• System.out.println("Using Previous(Print in reverse order)");
• while(liter.hasPrevious())
• {
• System.out.println(liter.previous());
• }
• // toArray
• System.out.println("2nd to array");
• Object[] o1 = al.toArray();
• for (int i1 = 0; i1<o1.length; i1++) {
• System.out.println(o1[i1]);
• }
• }
• }
Vector
• A Vector is basically the same as an ArrayList,
• Vector() methods are synchronized for thread safety.
• package com.jft.collections;
• import java.util.Enumeration; import java.util.Iterator; import java.util.Vector;
• public class VectorTest {
• public static void main(String[] args) {
• Vector v = new Vector();
• System.out.println(v);
• System.out.println(v.size());
• System.out.println(v.capacity());
• v.addElement("A");
• v.addElement("B");
• v.add("C");
• v.add("D");
• System.out.println(v);
• Enumeration e = v.elements();
• while (e.hasMoreElements()) {
• String str = e.nextElement().toString();
• System.out.println(str);
• }
• Iterator i = v.iterator();
• while (i.hasNext()){
• String str = i.next().toString();
• System.out.println(str);
• }}}
Differences
ArrayList Vector
Not Synchronized Synchronized
Iterator (To retrieve values) ListIterator(Superclass of Iterator)
Forward only (Iterate over a collection and
get values)
Both Forward & Reverse
Cant add elements to collection& Cant get
index (element)
Can add
Cant replace existing objects with new
object
Can replace using
while (liter.hasNext()) {
Object element = litr.next();
reference.set (element +” + ”) }
Iterator Enumeration
It is a collection framework interface Legacy (old) interface
Can also Remove elements Can only read elements
To access elements of AL, Vector, LL,
HS,TS, LHS
To access elements of vector only
* Array, ArrayList, Vector – Elements stored in indexing notation size by size
• While using indexing notation, the following error will occur:
- Inserting & Deleting element at specified index is time consuming.
- Solve this problem by using LinkedList – Elements will be stored in different memory
Locations and will be linked with address, such that insertion or deletion is faster.
LinkedList
- It provides a linked-list data structure.
- A LinkedList List is ordered by index position, like ArrayList, except that the elements are
doubly-linked to one another.
- This linkage gives you new methods beyond what you get from the List interface) for adding and
removing from the beginning or end, which makes it an easy choice for implementing a stack or
queue.
LinkedList l1=new LinkedList();
2 new methods in LinkedList:
void addFirst(Object obj)
void addLast(Object obj)
• package com.jft.collections;
• import java.util.*;
• public class LinkedListDemo {
• public static void main(String args[]) {
• LinkedList ll = new LinkedList();
• ll.add("a");
• ll.add("b");
• ll.add("c");
• System.out.println(ll);
• ll.addFirst("1");
• System.out.println(ll);
• ll.addLast("0");
• System.out.println(ll);
• ll.removeFirst();
• System.out.println(ll);
• ll.removeLast();
• System.out.println(ll);
• ll.remove();
• System.out.println(ll);
• }
• }
• public class Person {
• String name;
• int age;
• public Person(String n , int a) {
• name = n;
• age = a;
• }
• public String getName() {
• return name;
• }
• public void setName(String name) {
• this.name = name;
• }
• public int getAge() {
• return age;
• }
• public void setAge(int age) {
• this.age = age;
• }
• @Override
• public String toString() {
• return "name= "+name + " age= "+age;
• }
• /*boolean equals(Person p){
• if(this.name.equals(p.name)&& this.age == p.age){
• return true;
• }
• return false;
• }*/
• }
• package com.jft.collections;
• import java.util.ArrayList;
• import java.util.LinkedList;
• public class LinkedListDemo1 {
• public static void main(String[] args) {
• Person p1 = new Person("Allan",20);
• Person p2 = new Person("Robert",20);
• Person p3 = new Person("John",20);
• Person p4 = new Person("Hellen",20);
• Person p5 = new Person("Elen",20);
• Person p6 = new Person("Daisy",20);
• LinkedList l1 = new LinkedList();
• l1.add(p1);
• l1.add(p2);
• l1.add(p3);
• l1.add(p4);
• l1.add(p5);
• l1.add(null);
• l1.add(null);
• System.out.println(l1);
• //remove at specific index
• l1.remove(0);
• System.out.println(l1);
• //size
• System.out.println(l1.size());
• int i = l1.indexOf(p3);
• System.out.println(i);
• System.out.println(l1);
• l1.set(2, p6);
• System.out.println(l1);
• System.out.println("Is Person Daisy Available?"+l1.contains(p6));
• Object a[] = l1.toArray();
• for (i=0;i<a.length;i++){
• System.out.print(a[i]);
• }
• //Linked List Specific methods
• Person p7= new Person("Peter",20);
• Person p8= new Person("Tom",20);
• l1.addFirst(p7);
• l1.addLast(p8);
• System.out.println();
• System.out.println(l1);
• Object o1 = l1.getFirst();
• Object o2 = l1.getLast();
• System.out.println(o1);
• System.out.println(o2);
• l1.removeFirst();
• l1.removeLast();
• System.out.println(l1);
• /**/
• l1.clear();
• System.out.println(l1);
• }
• }
Differences
ArrayList LinkedList
Elements will be stored side by side with
indexing notation
Elements will be stored randomly
Elements will be accessed sequentially Elements will be accessed randomly
because it is implementing random access
marker interface
Insertion & Deletion are difficult Insertion & Deletion are easier
Uses less memory than LL Uses more memory in order to store
address
Set Interface
- A Set cares about uniqueness—it doesn’t allow duplicates. Therefore, the add( )
method returns false if an attempt is made to add duplicate elements to a set.
HashSet
- A HashSet is an unsorted, unordered Set.
- It uses the hashcode of the object being inserted, so the more efficient your
hashCode() implementation the better access performance you’ll get.
- Use this class when you want a collection with no duplicates and you don’t care
about order when you iterate through it.
- one null element allowed.
Eg:
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
Output: [c,d,a,e.b,f]
• import java.util.HashSet;
• public class HashSetDemo {
• public static void main(String[] args) {
• HashSet hs = new HashSet();
• hs.add("A");
• hs.add("B");
• hs.add("C");
• hs.add("D");
• hs.add("E");
• hs.add("F");
• hs.add("F");
• hs.add("A");
• hs.add(null);
• System.out.println(hs);
• System.out.println(hs.contains("F"));
• System.out.println(hs.isEmpty());
• System.out.println(hs.contains("A"));
• hs.remove("F");
• System.out.println(hs);
• System.out.println(hs.size());
• System.out.println(hs.getClass());
• hs.remove(null);
• System.out.println(hs);
• // hs.clear();
• System.out.println(hs);
• }}
LinkedHashSet
- A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked
List across all elements.
- Use this class instead of HashSet when you care about the iteration order; when
you iterate though a HashSet the order is unpredictable, while a LinkedHashSet lets
you iterate through the elements in the order in which they were inserted.
- Optionally, you can construct a LinkedHashSet so that it maintains the order in
which elements were last accessed, rather than the order in which elements were
inserted.
- one null element allowed.
- The output of the above code will be;
[B, A, D, E, C, F]
• import java.util.LinkedHashSet;
• public class LinkedHashSetDemo {
• public static void main (String args[]) {
• LinkedHashSet lhs = new LinkedHashSet();
• lhs.add("A");
• lhs.add("B");
• lhs.add("C");
• lhs.add("D");
• lhs.add("E");
• lhs.add("F");
• lhs.add("F");
• lhs.add("A");
• lhs.add(null);
• System.out.println(lhs);
• System.out.println(lhs.contains("D"));
• System.out.println(lhs.isEmpty());
• System.out.println(lhs.size());
• }
• }
TreeSet
- TreeSet provides an implementation of the Set interface that uses a tree
for storage.
- Objects are stored in sorted, ascending order.
- Access and retrieval times are quite fast, which makes TreeSet an
excellent choice when storing large amounts of sorted information that must
be found quickly.
- null gives exception at run time, so null is not allowed.
Application: useful for storing project-management information.
• package com.jft.collections;
• import java.util.TreeSet;
• public class TreeSetDemo {
• public static void main(String[] args) {
• TreeSet ts = new TreeSet();
• ts.add("A");
• ts.add("B");
• ts.add("C");
• ts.add("F");
• ts.add("F");
• ts.add("A");
• ts.add("D");
• ts.add("E");
• // ts.add(null);
• System.out.println(ts);
• System.out.println(ts.contains("D"));
• System.out.println(ts.isEmpty());
• System.out.println(ts.size());
• }
• }
Map Interface
• A map is an object that stores associations between keys and values, or
key/value pairs. Given a key, you can find its value.
- A Map cares about unique identifiers.
- Map maps a unique key (the ID) to a specific value, where both the key
and the value are of course objects.
- The keys must be unique, but the values may be duplicated.
- Some maps can accept a null key and null values, others cannot.
• Interface:
– Map.Entry Describes an element (a key/value pair) in a map. This is an inner
class of Map.
• entrySet( ) - returns a Set that contains the elements in the map
• keySet() - obtains a collection-view of the keys.
• values( ) - obtains a collection-view of the values.
• AbstractMap is a superclass for all concrete map implementations
• put() - Associates the specified value with the specified key in this map
• get() – Returns the value to which the specified key is mapped in this identity hash
map
• putAll() - Copies all of the mappings from the specified map to this map.
– These mappings will replace any mappings that this map had for any of the keys
currently in the specified map
• getkey() - Returns the key corresponding to this entry.
• getvalue() - Returns the value corresponding to this entry
HashMap
- The HashMap class uses a hash table to implement the Map interface.
- This allows the execution time of basic operations, such as get( ) & put( ),
to remain constant even for large sets.
- No Iteration order.
- Allows null
HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
HashTable (no null)
- Hashtable is the synchronized counterpart to HashMap.
- stores key/value pairs in a hash table
• specify an object that is used as a key, and the value that you want linked to
that key.
• The key is then hashed, and the resulting hash code is used as the index at
which the value is stored within the table.
LinkedHashMap
- Like its Set counterpart, LinkedHashSet, the LinkedHashMap collection
maintains insertion order (or, optionally, access order or Iteration order)
- It will be somewhat slower than HashMap for adding and removing
elements.
TreeMap
- TreeMap is a sorted Map.
• Application: TreeMap would make an excellent collection to hold the
directory structure of a set of files
• import java.util.Collection;import java.util.HashMap;import
java.util.Hashtable;import java.util.Iterator;
• import java.util.Map;import java.util.Set;import java.util.TreeMap;import
java.util.Map.Entry;
• public class HashTableDemo {
• public static void main(String[] args) {
• /*System.out.println("Using Hashtable");
• Hashtable ht = new Hashtable();
• ht.put("Sid", 99); ht.put("Phone", 99999);ht.put("Name", "Chandra");
• ht.put("email", "sri@sri.com"); ht.put("a", "99"); ht.put("b", "66");
• //ht.put("b", null);
• //ht.put(null, "C"); ht.put(new Long(66), "d");
• System.out.println(ht);
• System.out.println("Hashtable s "+ ht.get("a"));*/
• /*
• System.out.println("Using HashMap");
• HashMap hm = new HashMap();
• hm.put("Sid", 99); hm.put("Sname", "Chandra"); hm.put("a", "99");
• hm.put("email", "sri@sri.com"); hm.put("b", "99"); hm.put("Phone", 99999);
• hm.put(null, null);
• hm.put(new Long(66), "d");
• System.out.println(hm);
• System.out.println(hm.get("Phone"));
• */
• /*
• System.out.println("Using TreeMap");
• TreeMap tm = new TreeMap();
• tm.put("Sid", 99);
• tm.put("Sname", "Chandra");
• tm.put("a", "99");
• tm.put("email", "sri@sri.com");
• tm.put("b", null);
• tm.put("Phone", 99999);
• // tm.put(null, "x");
• //tm.put(new Long(66), "d");
• tm.put("address",new Integer(567));
• System.out.println(tm);
• System.out.println();
• Collection col = hm.values();
• Iterator it = col.iterator();
• while (it.hasNext()) {
• System.out.println(it.next());
• }
• System.out.println(hm.size());
• System.out.println(hm);
• hm.putAll(tm);
• System.out.println(hm.size());
• /* System.out.println("Using Keyset");
• Set s = hm.keySet();
• System.out.println(s);
• Iterator i = s.iterator();
• while(i.hasNext()){ // System.out.println(i.next());String key = null;String val = null;
• Object ol = i.next();
• if(ol!=null)
• { key = ol.toString(); }
• Object o2 = hm.get(key);
• if (o2 != null)
• { val = o2.toString();}
• System.out.println("Inside keyset");
• System.out.println(key + "..." +val);
• */
• /*System.out.println("Using EntrySet");
• Set ss = hm.entrySet();
• Iterator ii = ss.iterator();
• while(ii.hasNext()) { String key1 = null; String val1 = null;
• Map.Entry me = (Entry) ii.next();
• Object o1 = me.getKey();
• Object o3 = me.getValue();
• if (o1!=null)
• { key1 = o1.toString(); }
• if (o3!=null)
• { val1 = o3.toString(); }
• System.out.println(key1 +"...." +val1);
• }*/
• }}}
Differences
HashMap Hashtable
Accessible in collection framework Legacy class
Not synchronized Synchronized
Allows null keys & null values Doesn’t allow null keys & null values
HashMap TreeMap
Unordered Sorted & Ordered
Allows null keys & null values Doesn’t allow null keys & null values
Allows different types of keys Allows similar types of keys
Comparators
• Comparator interface defines two methods: compare( ) and equals( )
• A comparator object is capable of comparing two different objects.
• The class is not comparing its instances, but some other class’s instances.
• This comparator class must implement the java.lang.Comparator interface
• It implements the compare( ) method - Compares its two arguments for order.
• This method compares o1 and o2 objects.
• Returned int value has the following meanings.
• positive – o1 is greater than o2
• zero – o1 equals to o2
• negative – o1 is less than o1
• // compareTo() - Compares two strings lexicographically.
• import java.util.ArrayList;
• import java.util.Collections;
• import java.util.Comparator;
• public class SortArrayListInDescendingOrderExample {
• public static void main(String args[]){
• ArrayList al = new ArrayList();
• // al.add(new Integer(99));
• al.add("A");
• al.add("B");
• al.add("C");
• al.add("D");
• al.add("Srinivas");
• al.add("hari@hari.com");
• // System.out.println(al);
• Comparator cmp = Collections.reverseOrder();
• System.out.println("Before sorting"+al);
• Collections.sort(al,cmp);
• System.out.println("After sorting"+al);
• }}
• class Employee{
• private int age;
• private String name;
• public void setAge(int age){
• this.age=age;}
• public int getAge(){
• return this.age;}
• public void setName(String name){
• this.name=name;}
• public String getName(){
• return this.name;} }
• class AgeComparator implements Comparator{
• public int compare(Object emp1, Object emp2){
• //parameter are of type Object, so we have to downcast it to Employee objects
• int emp1Age = ( (Employee) emp1).getAge();
• int emp2Age = ( (Employee) emp2).getAge();
• if( emp1Age > emp2Age )
• return 1;
• else if( emp1Age < emp2Age )
• return -1;
• else
• return 0;
• }}
• class NameComparator implements Comparator{
• public int compare(Object emp1, Object emp2){
• //parameter are of type Object, so we have to downcast it to Employee objects
• String emp1Name = ( (Employee) emp1 ).getName();
• String emp2Name = ( (Employee) emp2 ).getName();
• //uses compareTo method of String class to compare names of the employee
• return emp1Name.compareTo(emp2Name);
• }}
• public class JavaComparatorExample{
• public static void main(String args[]){
• /*Employee array which will hold employees */
• Employee employee[] = new Employee[2];
• //set different attributes of the individual employee.
• employee[0] = new Employee();
• employee[0].setAge(40);
• employee[0].setName("Joe");
• employee[1] = new Employee();
• employee[1].setAge(20);
• employee[1].setName("Mark");
• System.out.println("Order of employee before sorting is");
• //print array as is.
• for(int i=0; i < employee.length; i++){
• System.out.println( "Employee " + (i+1) + " name :: " + employee[i].getName() + ", Age :: " +
employee[i].getAge());
• }
• /*Sort method of the Arrays class sorts the given array.
• Signature of the sort method is,
• static void sort(Object[] object, Comparator comparator)
• IMPORTANT: All methods defined by Arrays class are static.
• Arrays class serve as a utility class. */
• /*Sorting array on the basis of employee age by passing AgeComparator */
• //Arrays.sort(employee, new AgeComparator());
• Arrays.sort(employee, new AgeComparator());
• System.out.println("nnOrder of employee after sorting by employee age is");
• for(int i=0; i < employee.length; i++){
• System.out.println( "Employee " + (i+1) + " name :: " + employee[i].getName() + ",
Age :: " + employee[i].getAge());
• }
• /* Sorting array on the basis of employee Name by passing NameComparator */
• Arrays.sort(employee, new NameComparator());
• System.out.println("nnOrder of employee after sorting by employee name is");
• for(int i=0; i < employee.length; i++){
• System.out.println( "Employee " + (i+1) + " name :: " + employee[i].getName() + ",
Age :: " + employee[i].getAge()); }}}
• import java.util.*;
• class Student {
• private String name;
• private int regNum;
• Student(String nameOfStud, int regNum) {
• this.name = nameOfStud;
• this.regNum = regNum;
• }
• public String getName() {
• return name;
• }
• public int getRegNum() {
• return regNum;
• }
• public String toString() {
• return this.name + " " + this.regNum;
• }}
• class MyCompare implements Comparator {
• public int compare(Object obj1, Object obj2) {
• // Student s1 = (Student) obj1;
• // Student s2 = (Student) obj2;
• Student st1 = (Student) obj1;
• Student st2 = (Student) obj2;
• return (st1.getName().compareTo(st2.getName()));
• }
• /*public boolean equals(Object obj1) {
• return this.equals(obj1);
• }*/
• }
• public class ComparatorExample {
• public static void main(String args[]) {
• // create students;
• Student s1 = new Student("Mubashir", 123);
• Student s2 = new Student("Ahmed", 456);
• Student s3 = new Student("Arindam", 321);
• Student s4 = new Student("Debjit", 567);
• Student s5 = new Student("Nandu", 890);
• // create a new TreeSet
• //MyCompare myc = new MyCompare();
• //TreeSet ts = new TreeSet(myc);
• TreeSet ts = new TreeSet(new MyCompare());
• ts.add(s1);
• ts.add(s2);
• ts.add(s3);
• ts.add(s4);
• ts.add(s5);
• // Print the tree
• System.out.println("Elements in the TreeSet: ");
• Iterator it = ts.iterator();
• while(it.hasNext()) {
• System.out.println(it.next());
• }
• }
• }

12_-_Collections_Framework

  • 1.
    Collections Framework • Collectionrepresents a group of objects, known as its elements • Group of classes and interface. • Can store objects in collection classes.
  • 2.
    • (lowercase c)collection framework represents any of the data structures in which objects are stored & retrieved. • (Uppercase C ends with s) Collections – java.util.Collections class – holds static utility methods. • (Uppercase C) Collection is an Interface set the standard for Collection classes so that they will have uniform method names. • The five legacy classes: Vector, HashTable, Properties, Directory, Stack and one legacy interface: Enumeration • There are some problems with the above legacy classes. In order to avoid those problems, SUN has introduced Collection framework in Java 2. • Three categories: • List - Collection of object with duplicate • Set - Collection of object without duplicate • Map - Collection of key / value pairs
  • 4.
    Collections - The java.utilpackage contains one of Java’s most powerful subsystems: collections. Collections were added by the initial release of Java 2, and enhanced by Java 2,version 1.4. A collection is a group of objects - In addition to collections, java.util contains a wide assortment of classes and interfaces that support a broad range of functionality. - 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. i. The framework had to be high-performance. The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hash tables) are highly efficient. ii. The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability. iii. Extending and/or adapting a collection had to be easy.
  • 6.
    Collection Interfaces The collectionsframework defines several interfaces. Beginning with the collection interfaces is necessary because they determine the fundamental nature of the collection classes But there are sub flavors within those three types:
  • 7.
    Ordered - When acollection is ordered, it means you can iterate through the collection in a specific (not-random) order. - A Hashtable collection is not ordered. Although the Hashtable itself has internal logic to determine the order (based on hashcodes and the implementation of the collection itself), you won’t find any order when you iterate through the Hashtable. - An ArrayList, however, keeps the order established by the elements’ index position (just like an array). - LinkedHashSet keeps the order established by insertion, so the last element inserted is the last element in the LinkedHashSet (as opposed to an ArrayList where you can insert an element at a specific index position). Sorted - For a collection of String objects, then, the natural order is alphabetical. - For Integer objects, the natural order is by numeric value. - A sorted collection means a collection sorted by natural order. - And natural order is defined by the class of the objects being sorted
  • 8.
  • 10.
    List Interface The Listinterface extends Collection and declares the behavior of a collection that stores a sequence of elements. Elements can be inserted or accessed by their position in the list, using a zero-based index. A list may contain duplicate elements. The three List implementations are described in the following section. • (Insertion Order, Elements are stored by index, Duplicates are allowed, Null element is allowed) ArrayList ArrayList supports dynamic arrays that can grow as needed. In Java, standard 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. But, sometimes, you may not know until run time precisely how large of an array you need. To handle this situation, the collections framework defines ArrayList. Creation of Arraylist: ArrayList name_of_the _arraylist=new ArrayList(); Eg: ArrayList al=new ArrayList();
  • 11.
    Array ArrayList Size ofan array is fixed because, you need to provide the size when creating an array Size of an ArrayList is growable, So no need to specify size When array of size ‘n’ with m elements, then repeat For loop n times to access m elements, so that (n-m) times loop will be repeated unnecessarily. Using Iterator, we can access only the available elements, So no waste of time. Exception is possible in case m > n No Exception problem Retrieval is faster.
  • 12.
    Array ArrayList Object o[] = new Object[10]; ArrayList al = new ArrayList(); o[0] = new String(“hello”); al.add(new String("Srinivas")); o[1] = new Integer(99); al.add(new Student(99)) o[2] = new Student[10, “var”]; al.add(new Student(or ,”99”)) for (i = 0; I < o.length; i++) { System.out.println(o[i]); } Iterator i = al.iterator(); while (i.hasNext()) { System.out.println(i.next()); }
  • 13.
    • import java.util.*; •class ArrList1 { • public static void main (String args[]) • { • ArrayList al = new ArrayList(); • al.add("A"); • al.add("B"); • al.add("d"); • System.out.println("al " +al); • al.add("C"); • al.set(0, "AA"); • al.add(1, "9"); • System.out.println("al " +al); • // boolean b = al.contains("C"); • // System.out.println("al contains c " +b); • System.out.println("al contains C " +al.contains("C")); • // al.clear(); • // al.get(2); • System.out.println("al 2 " +al.get(2)); • al.set(0,"1"); • System.out.println("al " +al);
  • 14.
    • ArrayList s= (ArrayList) al.clone(); • System.out.println("al clone " +s); • /*// al.remove("B"); • System.out.println("al removes " +al.remove("B")); • System.out.println("al " +al); • System.out.println("al removes " +al.remove("B")); • System.out.println("al " +al); • /*al.add (2, "B"); • System.out.println("al added" +al); • ArrayList al1 = new ArrayList(); • al1.add("1");al1.add("2");al1.add("3"); • System.out.println(al == al1); • System.out.println(al.equals(al1)); • al.add(al1);System.out.println("al with al1 " +al); • System.out.println("al size " +al.size()); • al.remove("C"); • System.out.println("al removes C then " +al); • System.out.println("al " + al.contains("al1")); • al.removeAll(al1); • System.out.println("al after " +al); • al.addAll(al1); • System.out.println("al after add all" +al); • al.retainAll(al1);
  • 15.
    • import java.util.*; •public class ArrayListTest2 { • public static void main(String[] args) { • ArrayList al = new ArrayList(); al.add(new Integer(99));System.out.println(al);al.add("Srinivas");al.add("hari@hari.com"); • System.out.println(al); System.out.println(al.size()); System.out.println(al.isEmpty()); • // using toArray() method • System.out.println("using toArray()"); • int len= al.size(); • Object[] o = new Object[len]; • o = al.toArray(); • for (int i = 0; i < o.length; i++) { • System.out.println(o[i]); • } • // using Iterators • System.out.println("using Iterators "); • Iterator iter = al.iterator(); • while(iter.hasNext()){ • System.out.println(iter.next()); • } • // using ListIterator • System.out.println("using ListIterator"); • ListIterator liter = al.listIterator(); • while (liter.hasNext()) • {System.out.println(liter.next());} • System.out.println("Using Previous(Print in reverse order)"); • while(liter.hasPrevious()) • {System.out.println(liter.previous());}
  • 16.
    • // usingListIterator SET method Assigns obj to the current element • System.out.println("using ListIterator"); • ListIterator liter = al.listIterator(); • while (liter.hasNext()) • { • Object element = liter.next(); • liter.set(element + "+"); • } • System.out.println("Modified contents" ); • Iterator it1 = al.iterator(); • while(it1.hasNext()) { • Object element = it1.next(); • System.out.println(element+ ""); • } • System.out.println("Using Previous(Print in reverse order)"); • while(liter.hasPrevious()) • { • System.out.println(liter.previous()); • } • // toArray • System.out.println("2nd to array"); • Object[] o1 = al.toArray(); • for (int i1 = 0; i1<o1.length; i1++) { • System.out.println(o1[i1]); • } • } • }
  • 17.
    Vector • A Vectoris basically the same as an ArrayList, • Vector() methods are synchronized for thread safety. • package com.jft.collections; • import java.util.Enumeration; import java.util.Iterator; import java.util.Vector; • public class VectorTest { • public static void main(String[] args) { • Vector v = new Vector(); • System.out.println(v); • System.out.println(v.size()); • System.out.println(v.capacity()); • v.addElement("A"); • v.addElement("B"); • v.add("C"); • v.add("D"); • System.out.println(v); • Enumeration e = v.elements(); • while (e.hasMoreElements()) { • String str = e.nextElement().toString(); • System.out.println(str); • } • Iterator i = v.iterator(); • while (i.hasNext()){ • String str = i.next().toString(); • System.out.println(str); • }}}
  • 18.
    Differences ArrayList Vector Not SynchronizedSynchronized Iterator (To retrieve values) ListIterator(Superclass of Iterator) Forward only (Iterate over a collection and get values) Both Forward & Reverse Cant add elements to collection& Cant get index (element) Can add Cant replace existing objects with new object Can replace using while (liter.hasNext()) { Object element = litr.next(); reference.set (element +” + ”) } Iterator Enumeration It is a collection framework interface Legacy (old) interface Can also Remove elements Can only read elements To access elements of AL, Vector, LL, HS,TS, LHS To access elements of vector only
  • 19.
    * Array, ArrayList,Vector – Elements stored in indexing notation size by size • While using indexing notation, the following error will occur: - Inserting & Deleting element at specified index is time consuming. - Solve this problem by using LinkedList – Elements will be stored in different memory Locations and will be linked with address, such that insertion or deletion is faster. LinkedList - It provides a linked-list data structure. - A LinkedList List is ordered by index position, like ArrayList, except that the elements are doubly-linked to one another. - This linkage gives you new methods beyond what you get from the List interface) for adding and removing from the beginning or end, which makes it an easy choice for implementing a stack or queue. LinkedList l1=new LinkedList(); 2 new methods in LinkedList: void addFirst(Object obj) void addLast(Object obj)
  • 20.
    • package com.jft.collections; •import java.util.*; • public class LinkedListDemo { • public static void main(String args[]) { • LinkedList ll = new LinkedList(); • ll.add("a"); • ll.add("b"); • ll.add("c"); • System.out.println(ll); • ll.addFirst("1"); • System.out.println(ll); • ll.addLast("0"); • System.out.println(ll); • ll.removeFirst(); • System.out.println(ll); • ll.removeLast(); • System.out.println(ll); • ll.remove(); • System.out.println(ll); • } • }
  • 21.
    • public classPerson { • String name; • int age; • public Person(String n , int a) { • name = n; • age = a; • } • public String getName() { • return name; • } • public void setName(String name) { • this.name = name; • } • public int getAge() { • return age; • } • public void setAge(int age) { • this.age = age; • } • @Override • public String toString() { • return "name= "+name + " age= "+age; • } • /*boolean equals(Person p){ • if(this.name.equals(p.name)&& this.age == p.age){ • return true; • } • return false; • }*/ • }
  • 22.
    • package com.jft.collections; •import java.util.ArrayList; • import java.util.LinkedList; • public class LinkedListDemo1 { • public static void main(String[] args) { • Person p1 = new Person("Allan",20); • Person p2 = new Person("Robert",20); • Person p3 = new Person("John",20); • Person p4 = new Person("Hellen",20); • Person p5 = new Person("Elen",20); • Person p6 = new Person("Daisy",20); • LinkedList l1 = new LinkedList(); • l1.add(p1); • l1.add(p2); • l1.add(p3); • l1.add(p4); • l1.add(p5); • l1.add(null); • l1.add(null); • System.out.println(l1); • //remove at specific index • l1.remove(0); • System.out.println(l1); • //size • System.out.println(l1.size()); • int i = l1.indexOf(p3); • System.out.println(i); • System.out.println(l1); • l1.set(2, p6); • System.out.println(l1); • System.out.println("Is Person Daisy Available?"+l1.contains(p6));
  • 23.
    • Object a[]= l1.toArray(); • for (i=0;i<a.length;i++){ • System.out.print(a[i]); • } • //Linked List Specific methods • Person p7= new Person("Peter",20); • Person p8= new Person("Tom",20); • l1.addFirst(p7); • l1.addLast(p8); • System.out.println(); • System.out.println(l1); • Object o1 = l1.getFirst(); • Object o2 = l1.getLast(); • System.out.println(o1); • System.out.println(o2); • l1.removeFirst(); • l1.removeLast(); • System.out.println(l1); • /**/ • l1.clear(); • System.out.println(l1); • } • }
  • 24.
    Differences ArrayList LinkedList Elements willbe stored side by side with indexing notation Elements will be stored randomly Elements will be accessed sequentially Elements will be accessed randomly because it is implementing random access marker interface Insertion & Deletion are difficult Insertion & Deletion are easier Uses less memory than LL Uses more memory in order to store address
  • 25.
    Set Interface - ASet cares about uniqueness—it doesn’t allow duplicates. Therefore, the add( ) method returns false if an attempt is made to add duplicate elements to a set. HashSet - A HashSet is an unsorted, unordered Set. - It uses the hashcode of the object being inserted, so the more efficient your hashCode() implementation the better access performance you’ll get. - Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it. - one null element allowed. Eg: HashSet hs = new HashSet(); // add elements to the hash set hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); Output: [c,d,a,e.b,f]
  • 26.
    • import java.util.HashSet; •public class HashSetDemo { • public static void main(String[] args) { • HashSet hs = new HashSet(); • hs.add("A"); • hs.add("B"); • hs.add("C"); • hs.add("D"); • hs.add("E"); • hs.add("F"); • hs.add("F"); • hs.add("A"); • hs.add(null); • System.out.println(hs); • System.out.println(hs.contains("F")); • System.out.println(hs.isEmpty()); • System.out.println(hs.contains("A")); • hs.remove("F"); • System.out.println(hs); • System.out.println(hs.size()); • System.out.println(hs.getClass()); • hs.remove(null); • System.out.println(hs); • // hs.clear(); • System.out.println(hs); • }}
  • 27.
    LinkedHashSet - A LinkedHashSetis an ordered version of HashSet that maintains a doubly-linked List across all elements. - Use this class instead of HashSet when you care about the iteration order; when you iterate though a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted. - Optionally, you can construct a LinkedHashSet so that it maintains the order in which elements were last accessed, rather than the order in which elements were inserted. - one null element allowed. - The output of the above code will be; [B, A, D, E, C, F]
  • 28.
    • import java.util.LinkedHashSet; •public class LinkedHashSetDemo { • public static void main (String args[]) { • LinkedHashSet lhs = new LinkedHashSet(); • lhs.add("A"); • lhs.add("B"); • lhs.add("C"); • lhs.add("D"); • lhs.add("E"); • lhs.add("F"); • lhs.add("F"); • lhs.add("A"); • lhs.add(null); • System.out.println(lhs); • System.out.println(lhs.contains("D")); • System.out.println(lhs.isEmpty()); • System.out.println(lhs.size()); • } • }
  • 29.
    TreeSet - TreeSet providesan implementation of the Set interface that uses a tree for storage. - Objects are stored in sorted, ascending order. - Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. - null gives exception at run time, so null is not allowed. Application: useful for storing project-management information.
  • 30.
    • package com.jft.collections; •import java.util.TreeSet; • public class TreeSetDemo { • public static void main(String[] args) { • TreeSet ts = new TreeSet(); • ts.add("A"); • ts.add("B"); • ts.add("C"); • ts.add("F"); • ts.add("F"); • ts.add("A"); • ts.add("D"); • ts.add("E"); • // ts.add(null); • System.out.println(ts); • System.out.println(ts.contains("D")); • System.out.println(ts.isEmpty()); • System.out.println(ts.size()); • } • }
  • 31.
    Map Interface • Amap is an object that stores associations between keys and values, or key/value pairs. Given a key, you can find its value. - A Map cares about unique identifiers. - Map maps a unique key (the ID) to a specific value, where both the key and the value are of course objects. - The keys must be unique, but the values may be duplicated. - Some maps can accept a null key and null values, others cannot. • Interface: – Map.Entry Describes an element (a key/value pair) in a map. This is an inner class of Map. • entrySet( ) - returns a Set that contains the elements in the map • keySet() - obtains a collection-view of the keys. • values( ) - obtains a collection-view of the values. • AbstractMap is a superclass for all concrete map implementations
  • 32.
    • put() -Associates the specified value with the specified key in this map • get() – Returns the value to which the specified key is mapped in this identity hash map • putAll() - Copies all of the mappings from the specified map to this map. – These mappings will replace any mappings that this map had for any of the keys currently in the specified map • getkey() - Returns the key corresponding to this entry. • getvalue() - Returns the value corresponding to this entry
  • 33.
    HashMap - The HashMapclass uses a hash table to implement the Map interface. - This allows the execution time of basic operations, such as get( ) & put( ), to remain constant even for large sets. - No Iteration order. - Allows null HashMap hm = new HashMap(); // Put elements to the map hm.put("John Doe", new Double(3434.34)); hm.put("Tom Smith", new Double(123.22)); hm.put("Jane Baker", new Double(1378.00)); hm.put("Todd Hall", new Double(99.22)); hm.put("Ralph Smith", new Double(-19.08));
  • 34.
    HashTable (no null) -Hashtable is the synchronized counterpart to HashMap. - stores key/value pairs in a hash table • specify an object that is used as a key, and the value that you want linked to that key. • The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table. LinkedHashMap - Like its Set counterpart, LinkedHashSet, the LinkedHashMap collection maintains insertion order (or, optionally, access order or Iteration order) - It will be somewhat slower than HashMap for adding and removing elements. TreeMap - TreeMap is a sorted Map. • Application: TreeMap would make an excellent collection to hold the directory structure of a set of files
  • 35.
    • import java.util.Collection;importjava.util.HashMap;import java.util.Hashtable;import java.util.Iterator; • import java.util.Map;import java.util.Set;import java.util.TreeMap;import java.util.Map.Entry; • public class HashTableDemo { • public static void main(String[] args) { • /*System.out.println("Using Hashtable"); • Hashtable ht = new Hashtable(); • ht.put("Sid", 99); ht.put("Phone", 99999);ht.put("Name", "Chandra"); • ht.put("email", "sri@sri.com"); ht.put("a", "99"); ht.put("b", "66"); • //ht.put("b", null); • //ht.put(null, "C"); ht.put(new Long(66), "d"); • System.out.println(ht); • System.out.println("Hashtable s "+ ht.get("a"));*/ • /* • System.out.println("Using HashMap"); • HashMap hm = new HashMap(); • hm.put("Sid", 99); hm.put("Sname", "Chandra"); hm.put("a", "99"); • hm.put("email", "sri@sri.com"); hm.put("b", "99"); hm.put("Phone", 99999); • hm.put(null, null); • hm.put(new Long(66), "d"); • System.out.println(hm); • System.out.println(hm.get("Phone")); • */
  • 36.
    • /* • System.out.println("UsingTreeMap"); • TreeMap tm = new TreeMap(); • tm.put("Sid", 99); • tm.put("Sname", "Chandra"); • tm.put("a", "99"); • tm.put("email", "sri@sri.com"); • tm.put("b", null); • tm.put("Phone", 99999); • // tm.put(null, "x"); • //tm.put(new Long(66), "d"); • tm.put("address",new Integer(567)); • System.out.println(tm); • System.out.println(); • Collection col = hm.values(); • Iterator it = col.iterator(); • while (it.hasNext()) { • System.out.println(it.next()); • } • System.out.println(hm.size()); • System.out.println(hm); • hm.putAll(tm); • System.out.println(hm.size());
  • 37.
    • /* System.out.println("UsingKeyset"); • Set s = hm.keySet(); • System.out.println(s); • Iterator i = s.iterator(); • while(i.hasNext()){ // System.out.println(i.next());String key = null;String val = null; • Object ol = i.next(); • if(ol!=null) • { key = ol.toString(); } • Object o2 = hm.get(key); • if (o2 != null) • { val = o2.toString();} • System.out.println("Inside keyset"); • System.out.println(key + "..." +val); • */ • /*System.out.println("Using EntrySet"); • Set ss = hm.entrySet(); • Iterator ii = ss.iterator(); • while(ii.hasNext()) { String key1 = null; String val1 = null; • Map.Entry me = (Entry) ii.next(); • Object o1 = me.getKey(); • Object o3 = me.getValue(); • if (o1!=null) • { key1 = o1.toString(); } • if (o3!=null) • { val1 = o3.toString(); } • System.out.println(key1 +"...." +val1); • }*/ • }}}
  • 38.
    Differences HashMap Hashtable Accessible incollection framework Legacy class Not synchronized Synchronized Allows null keys & null values Doesn’t allow null keys & null values HashMap TreeMap Unordered Sorted & Ordered Allows null keys & null values Doesn’t allow null keys & null values Allows different types of keys Allows similar types of keys
  • 39.
    Comparators • Comparator interfacedefines two methods: compare( ) and equals( ) • A comparator object is capable of comparing two different objects. • The class is not comparing its instances, but some other class’s instances. • This comparator class must implement the java.lang.Comparator interface • It implements the compare( ) method - Compares its two arguments for order. • This method compares o1 and o2 objects. • Returned int value has the following meanings. • positive – o1 is greater than o2 • zero – o1 equals to o2 • negative – o1 is less than o1 • // compareTo() - Compares two strings lexicographically.
  • 40.
    • import java.util.ArrayList; •import java.util.Collections; • import java.util.Comparator; • public class SortArrayListInDescendingOrderExample { • public static void main(String args[]){ • ArrayList al = new ArrayList(); • // al.add(new Integer(99)); • al.add("A"); • al.add("B"); • al.add("C"); • al.add("D"); • al.add("Srinivas"); • al.add("hari@hari.com"); • // System.out.println(al); • Comparator cmp = Collections.reverseOrder(); • System.out.println("Before sorting"+al); • Collections.sort(al,cmp); • System.out.println("After sorting"+al); • }}
  • 41.
    • class Employee{ •private int age; • private String name; • public void setAge(int age){ • this.age=age;} • public int getAge(){ • return this.age;} • public void setName(String name){ • this.name=name;} • public String getName(){ • return this.name;} } • class AgeComparator implements Comparator{ • public int compare(Object emp1, Object emp2){ • //parameter are of type Object, so we have to downcast it to Employee objects • int emp1Age = ( (Employee) emp1).getAge(); • int emp2Age = ( (Employee) emp2).getAge(); • if( emp1Age > emp2Age ) • return 1; • else if( emp1Age < emp2Age ) • return -1; • else • return 0; • }}
  • 42.
    • class NameComparatorimplements Comparator{ • public int compare(Object emp1, Object emp2){ • //parameter are of type Object, so we have to downcast it to Employee objects • String emp1Name = ( (Employee) emp1 ).getName(); • String emp2Name = ( (Employee) emp2 ).getName(); • //uses compareTo method of String class to compare names of the employee • return emp1Name.compareTo(emp2Name); • }} • public class JavaComparatorExample{ • public static void main(String args[]){ • /*Employee array which will hold employees */ • Employee employee[] = new Employee[2]; • //set different attributes of the individual employee. • employee[0] = new Employee(); • employee[0].setAge(40); • employee[0].setName("Joe"); • employee[1] = new Employee(); • employee[1].setAge(20); • employee[1].setName("Mark"); • System.out.println("Order of employee before sorting is"); • //print array as is. • for(int i=0; i < employee.length; i++){ • System.out.println( "Employee " + (i+1) + " name :: " + employee[i].getName() + ", Age :: " + employee[i].getAge()); • }
  • 43.
    • /*Sort methodof the Arrays class sorts the given array. • Signature of the sort method is, • static void sort(Object[] object, Comparator comparator) • IMPORTANT: All methods defined by Arrays class are static. • Arrays class serve as a utility class. */ • /*Sorting array on the basis of employee age by passing AgeComparator */ • //Arrays.sort(employee, new AgeComparator()); • Arrays.sort(employee, new AgeComparator()); • System.out.println("nnOrder of employee after sorting by employee age is"); • for(int i=0; i < employee.length; i++){ • System.out.println( "Employee " + (i+1) + " name :: " + employee[i].getName() + ", Age :: " + employee[i].getAge()); • } • /* Sorting array on the basis of employee Name by passing NameComparator */ • Arrays.sort(employee, new NameComparator()); • System.out.println("nnOrder of employee after sorting by employee name is"); • for(int i=0; i < employee.length; i++){ • System.out.println( "Employee " + (i+1) + " name :: " + employee[i].getName() + ", Age :: " + employee[i].getAge()); }}}
  • 44.
    • import java.util.*; •class Student { • private String name; • private int regNum; • Student(String nameOfStud, int regNum) { • this.name = nameOfStud; • this.regNum = regNum; • } • public String getName() { • return name; • } • public int getRegNum() { • return regNum; • } • public String toString() { • return this.name + " " + this.regNum; • }} • class MyCompare implements Comparator { • public int compare(Object obj1, Object obj2) { • // Student s1 = (Student) obj1; • // Student s2 = (Student) obj2; • Student st1 = (Student) obj1; • Student st2 = (Student) obj2; • return (st1.getName().compareTo(st2.getName())); • } • /*public boolean equals(Object obj1) { • return this.equals(obj1); • }*/ • }
  • 45.
    • public classComparatorExample { • public static void main(String args[]) { • // create students; • Student s1 = new Student("Mubashir", 123); • Student s2 = new Student("Ahmed", 456); • Student s3 = new Student("Arindam", 321); • Student s4 = new Student("Debjit", 567); • Student s5 = new Student("Nandu", 890); • // create a new TreeSet • //MyCompare myc = new MyCompare(); • //TreeSet ts = new TreeSet(myc); • TreeSet ts = new TreeSet(new MyCompare()); • ts.add(s1); • ts.add(s2); • ts.add(s3); • ts.add(s4); • ts.add(s5); • // Print the tree • System.out.println("Elements in the TreeSet: "); • Iterator it = ts.iterator(); • while(it.hasNext()) { • System.out.println(it.next()); • } • } • }