You are on page 1of 98

© People Strategists - Duplication is strictly prohibited

- www.peoplestrategists.com
Day 7
Collections

© People Strategists - Duplication is strictly prohibited


- www.peoplestrategists.com
Collections

© People Strategists - Duplication is strictly prohibited


- www.peoplestrategists.com
Working with Dates
• The java.util.Date class is used to work date and time.
• The following code snippet is used to print the current date and time:
Date d=new Date();
System.out.println(d);
• The following table displays some of the commonly used methods of
Date class:
Method Description
public int getDate() Returns the day of the month represented by the Date object.
public int getDay() Returns the day of the week represented by the Date object.
public int getYear() Returns an integer value, represented by the Date object
minus 1900.
Working with Dates (Contd.)
Method Description
public int getMonth() Returns a number representing the month represented by the Date object

public int getHours() Returns the hour represented by the Date object.

public int getMinutes() Returns the number of minutes past the hour represented by the Date object

public int getSeconds() Returns the number of seconds past the minute represented by the Date object.

• All the methods discussed in preceding table are deprecated. All the
methods are replaced by the get() method in java.util.Calendar class.
• However, the Date class is used as a bridge to format a Calendar
object using the java.text.DateFormat class.
Working with Dates (Contd.)
• An example to work with Date class:
import java.util.*;
public class TestDateTime {
@SuppressWarnings("deprecation")
public static void main(String args[]){
Date d=new Date();
System.out.println("Current date:"+d);
System.out.println("Day:"+d.getDay());
System.out.println("Month:"+d.getMonth());
Working with Dates (Contd.)
int y=d.getYear();
y+=1900;
System.out.println("Year:"+y);;
System.out.println("Hours:"+d.getHours());
System.out.println("Minutes:"+d.getMinutes());
System.out.println("Seconds:"+d.getSeconds());
}
}
Working with Dates (Contd.)
• The preceding code output will be:
Current date:Wed Jul 08 11:33:29 IST 2015
Day:3
Month:6
Year:2015
Hours:11
Minutes:33
Seconds:29
Working with Dates (Contd.)
• Similar, to Date class the Calendar class also allows to work with date
and time.
• The Calendar class is an abstract class. Therefore, the Calendar class
instance is obtained by invoking the static getInstance() method of
Calender class.
• The code snippet to obtain the instance of Calendar class:
Calendar c=Calendar.getInstance();
• The Calendar class defines calendar fields, such as YEAR, MONTH,
DAY_OF_MONTH, and HOUR.
Working with Dates (Contd.)
• An example to work with Calendar class:
import java.util.*;
public class TestDateTime {
public static void main(String args[]){
Calendar c=Calendar.getInstance();
System.out.println("Date:"+c.get(Calendar.DATE));
System.out.println("Year:"+c.get(Calendar.YEAR));
System.out.println("Month"+c.get(Calendar.MONTH));
System.out.println("Day:"+c.get(Calendar.DAY_OF_MONTH));
System.out.println("Day of
year:"+c.get(Calendar.DAY_OF_YEAR));
System.out.println("Hours:"+c.get(Calendar.HOUR));
}
}
Working with Dates (Contd.)
• The preceding code output will be:
Date:8
Year:2015
Month6
Day:8
Day of year:189
Hours:11
Working with Dates (Contd.)
• The java.text.DateFormat class is used to format date and time.
• The DateFormat class instance is obtained using the static method,
getDateInstance() of the DateFormat class.
• An example to work with DateFormat class:
import java.text.*;
import java.util.*;
public class TestDateTime {
public static void main(String args[]){
Calendar cObj = Calendar.getInstance();
DateFormat
dfDobj=DateFormat.getDateInstance(DateFormat.MEDIUM);
cObj.set(2015,6,8);
Date dateObj = cObj.getTime();
Working with Dates (Contd.)
System.out.println(dateObj);
System.out.println(dfDobj.format(dateObj));
}
}
• The preceding code output will be:
Wed Jul 08 12:30:38 IST 2015
Jul 8, 2015
• Similarly, the DateFormat.SHORT, will display the output as, 7/8/15
and DateFormat.LONG, will display the output as, July 8, 2015
Working with Dates (Contd.)
• The java.util.Locale class is used in conjunction with DateFormat class
to format date according to specific locale.
• The following code snippet creates an instance of Locale class.
Locale locIN=new Locale("it");
• In the preceding code snippet, it , is the language code of Italy.
• Similarly, Locale class instance can also be create as:
Locale locIN=new Locale("it","IT");
• In the preceding code snippet, it , is the language code of Italy and IT,
is the country code of Italy.
Working with Dates (Contd.)
• An example to work with Locale class:
import java.text.*;
import java.util.*;
public class TestDateTime {
public static void main(String args[]){
Calendar cObj = Calendar.getInstance();
cObj.set(2015,6,8);
Date dateObj = cObj.getTime();
Locale locIN=new Locale("it","IT");
DateFormat dfDobj=DateFormat.getDateInstance(DateFormat.FULL,locIN);
System.out.println(dfDobj.format(dateObj));
}
}

• The preceding code output will be:


mercoledì 8 luglio 2015
Generics
• Generic in Java provides compile time type-safety of code and
removing risk of the ClassCastException.
• Consider the following code:
public class Test {
private Object object;

public void set(Object object) {


this.object = object;
}
public Object get() {
return object;
}

}
Generics (Contd.)

public class GenericTest {


public static void main(String args[]) {
Test obj=new Test();
obj.set(new Integer(1));
System.out.println(obj.get());
obj.set(new Character('a'));
System.out.println(obj.get());
obj.set(new String("Hello"));
System.out.println(obj.get());

}
Generics (Contd.)
• The preceding code output will be:
1
a
Hello
• In the preceding code, the methods of Test class accept or return an
Object.
• Therefore, any object can be passed to the method.
• There is no way to verify, at compile time, how the class is used.
• To overcome this issue, generics are introduced in Java
Generics (Contd.)
• The implement generics in preceding example, following changes
must be done to the code:
class Test<T> {
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
• In the preceding code, a generic class Test is created with one
parameter.
Generics (Contd.)
public class GenericTest {
public static void main(String args[]) {
Test<Integer> obj = new Test<Integer>();
obj.set(new Integer(1));
System.out.println(obj.get());
}
}
• The preceding code output will be:
Generics (Contd.)
• In the preceding code, if the following statements are added to the
main() method of GenericTest class, compilation error will be raised:
obj.set(new Character('a'));
obj.set(new String("Hello"));
• Thus, generics ensures that the methods of Test class can accept only
Integer object.
Generics (Contd.)
• An example to create generic class with two parameter:
public class Test<T1, T2> {
private T1 t1;
private T2 t2;
public Test(T1 t1, T2 t2) {
this.t1 = t1;
this.t2 = t2;
}
Generics (Contd.)
public class GenericTest {
public static void main(String args[]) {
Test<Integer,String> obj1 = new
Test<Integer,String>(1,"Raj");
Test<Integer,String> obj2 = new
Test<Integer,String>(2,"Rina");
}
}
Generics (Contd.)
• You can create a generic class parameter by restricting it to a group of
object. This is achieved by extending the generic class parameter to a
super class.
• An example to create generic class parameter extending super class:
class Shapes {
void displayShapes() {
System.out.println("Shapes");
}
}
Generics (Contd.)
class Rectangle extends Shapes {
public void displayShapes() {
System.out.println("Rectangle");
}
}

class Pentagon {
void displayPentagon() {
System.out.println("Pentagon");
}
}
Generics (Contd.)
public class Test<T extends Shapes> {
private T t;

public Test(T t) {
this.t = t;
}

void callTest() {
t.displayShapes();
}

}
Generics (Contd.)
public class GenericTest {
public static void main(String args[]) {
Rectangle rect=new Rectangle();
Test <Rectangle> tObj=new Test<Rectangle>(rect);
tObj.callTest();
}
}
• The preceding code output will be:
Rectangle
• In the preceding code, if the Rectangle class does not extends Shapes
class then a compilation error will be raised in the main() method.
Generics (Contd.)
• You can create a generic parameter of unknown type using the
wildcard, ?.
• An example to create a generic parameter of unknown type:
class Shapes {
int height,width;
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
Generics (Contd.)
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
}
class Rectangle extends Shapes {
Rectangle(int h, int w){
height=h;
width=w;
}
}
Generics (Contd.)
public class Test<T extends Shapes> {
private T t;
public Test(T t) {
this.t = t;
}
public int getWidthTest() {
return t.getWidth();
}
public int getHeightTest() {
return t.getHeight();
}
Generics (Contd.)
boolean callTest(Test<?> tObj) {
boolean result=false;
if(t.getHeight()==tObj.getHeightTest() &&
t.getWidth()==tObj.getWidthTest())
result=true;
return result;
}
}
Generics (Contd.)
public class GenericTest {
public static void main(String args[]) {
Rectangle rect1=new Rectangle(10,20);
Rectangle rect2=new Rectangle(10,21);
Test <Rectangle> tObj1=new Test<Rectangle>(rect1);
Test <Rectangle> tObj2=new Test<Rectangle>(rect2);
System.out.println("rect1 and rect 2 are
equal:"+tObj1.callTest(tObj2));
}
}
Generics (Contd.)
• The preceding code output will be:
rect1 and rect 2 are equal:false
Generics (Contd.)
• You set the bounds for a generic parameter of unknown type.
• The two types of bounds that can be set are upper bound and lower
bound.
• The upper bound is set using the extends keyword and lower bound is
set using the super keyword
Generics (Contd.)
• Consider the following hierarchy diagram of Book class:

Books

Computer Story

Hardware Software Fiction NonFiction


Generics (Contd.)
• Consider the following code snippet based on Books class to understand
the functionality of generic parameter of unknown type with upper and
lower bound:
public class Test<T extends Books> {
private T t;
void callTest(Test<?> tObj) {
}
void callTest1(Test<? extends Computer> tObj) {
}
void callTest2(Test<? super Story> tObj) {
}
}
Generics (Contd.)
• In the preceding code:
• The callTest() method can accept any object of type Books.
• The callTestExtends() method can accept any object of type Computer.
• The callTestSupper() method can accept only object of Book class or Story
class.
Collections
• The collections in java is a framework that provides an architecture to
store and manipulate the group of objects.
• The collection framework allows to perform operations, such as
searching, sorting, insertion, and deletion.
• The collection framework provides a set of utility classes and
interfaces to work with collection of objects.
• The utility classes and interfaces are packed inside java.util package.
Collections (Contd.)
• The hierarchy of collection framework is shown in the following
figure:
Collection Interface
• The Collection interface is used to pass around collections of objects
where maximum generality is desired.
• The following table lists the methods in Collection interface.
Method Description
public boolean add(Object element) Is used to insert an element in this collection.

public boolean addAll(collection c) Is used to insert the specified collection elements in the
invoking collection.
public boolean remove(Object element) Is used to delete an element from this collection.

public boolean removeAll(Collection c) Is used to delete all the elements of specified collection
from the invoking collection.
public boolean retainAll(Collection c) Is used to delete all the elements of invoking collection
except the specified collection.
Collection Interface (Contd.)

Method Description
public int size() Returns the total number of elements in the
collection.
public void clear() Removes the total no of element from the
collection.
public boolean contains(object element) Is used to search an element.

public boolean containsAll(Collection c) Is used to search the specified collection in this


collection.
public Iterator iterator() Returns an iterator.

public Object[] toArray() Converts collection into array.

public boolean isEmpty() Checks if collection is empty.

public boolean equals(Object element) Matches two collection.

public int hashCode() Returns the hashcode number for collection.


Iterator interface
• Iterator interface provides the facility of iterating the elements in
forward direction only.
• The following table lists the methods in Iterator interface:
Method Description
public boolean hasNext() Returns true if iterator has more elements.
public object next() Returns the element and moves the cursor pointer to
the next element.
public void remove() Removes the last elements returned by the iterator.
ListIterator interface
• ListIterator interface is used to traverse the element in backward and
forward direction.
• The following table lists the methods in ListIterator interface:
Method Description
public boolean hasPrevious() Returns true if this list iterator has more elements
when traversing the list in the reverse direction.
public Object previous() Returns the previous element in the list and moves
the cursor position backwards.
public boolean hasNext() Returns true if iterator has more elements.
public object next() Returns the element and moves the cursor pointer to
the next element.
public void remove() Removes the last elements returned by the iterator.
List Interface
• A List is an ordered Collection.
• Lists may contain duplicate elements.
• To work with List collection the following two classes are used:
• ArrayList
• LinkedList
ArrayList Class
• Java ArrayList class uses a dynamic array for storing the elements.
• A ArrayList class extends AbstractList class and implements List
interface.
• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because array works at the index
basis.
• In Java ArrayList class, manipulation is slow because a lot of shifting
needs to be occurred if any element is removed from the array list.
ArrayList Class (Contd.)
• An example to work with ArrayList:
import java.util.*;
class TestCollection{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Rajiv");
al.add("Viji");
al.add("Rajiv");
al.add("Jay");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
ArrayList Class (Contd.)
• The preceding code output will be:
Rajiv
Viji
Raj
Jay
LinkedList Class
• Java LinkedList class uses doubly linked list to store the elements. It
extends the AbstractList class and implements List and Deque
interfaces.
• Java LinkedList class can contain duplicate elements.
• Java LinkedList class maintains insertion order.
• Java LinkedList class is non synchronized.
• In Java LinkedList class, manipulation is fast because no shifting needs
to be occurred.
• Java LinkedList class can be used as list, stack or queue.
LinkedList Class
• An example to work with LinkedList class:
import java.util.*;
class TestCollection{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Rajiv");
al.add("Viji");
al.add("Rajiv");
al.add("Jay");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Set Interface
• A Set is a collection that cannot contain duplicate elements.
• To work with Set collection following classes can be used:
• HashSet
• TreeSet
HashSet Class
• The HashSet collections uses hashtable to store the elements.
• The HashSet class extends AbstractSet class and implements Set
interface.
• The HashSet collections contains unique elements only.
• An example to work with HastSet:
import java.util.*;
class TestCollection{
public static void main(String args[]){
HashSet<String> al=new HashSet<String>();
HashSet Class (Contd.)
al.add("Rajiv");
al.add("Viji");
al.add("Rajiv");
al.add("Jay");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
• The preceding code output will be:
Rajiv
Jay
Viji
TreeSet Class
• TreeSet collections contains unique elements only like HashSet.
• The TreeSet class implements NavigableSet interface that extends the
SortedSet interface.
• TreeSet collections sorts the elements in ascending order.
• An example to work with TreeSet:
import java.util.*;
class TestCollection{
public static void main(String args[]){
TreeSet<String> al=new TreeSet<String>();
TreeSet Class (Contd.)
al.add("Rajiv");
al.add("Viji");
al.add("Rajiv");
al.add("Jay");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
• The preceding code output will be:
Jay
Rajiv
Viji
Map Interface
• A Map collection contains values based on the key and value pair.
• Each pair is known as an entry.
• Map collections contains only unique elements.
• The following table lists the methods in Map interface:
Method Name Description

public Object put(object key,Object value) Is used to insert an entry in this map.

public void putAll(Map map) Is used to insert the specified map in this map.

public Object remove(object key) Is used to delete an entry for the specified key.

public Object get(Object key) Is used to return the value for the specified key.
Map Interface (Contd.)
Method Name Description

public boolean containsKey(Object key) Is used to search the specified key from this
map.
public boolean containsValue(Object Is used to search the specified value from this
value) map.
public Set keySet() Returns the Set view containing all the keys
public Set entrySet() Returns the Set view containing all the keys
and values.

• To work with Map collections following classes are used:


• HashMap
• TreeMap
HashMap Class
• A HashMap collection contains values based on the key.
• The HashMap class the Map interface and extends AbstractMap class.
• A HashMap collection contains only unique elements.
• A HashMap collection may have one null key and multiple null values.
• A HashMap collection maintains no order.
• An example to work with HashMap:
import java.util.*;
class TestCollection{
public static void main(String args[]){
HashMap<Integer,String> hm=new
HashMap<Integer,String>();
HashMap Class (Contd.)
hm.put(100,"Amay");
hm.put(101,"Viji");
hm.put(102,"Raj");

for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
• The preceding code output:
102 Raj
100 Amay
101 Viji
TreeMap Class
• A TreeMap collection contains values based on the key.
• A TreeMap class implements the NavigableMap interface and extends
AbstractMap class.
• A TreeMap collection contains only unique elements.
• A TreeMap collection cannot have null key but can have multiple null
values.
• A TreeMap collection maintains ascending order.
TreeMap Class (Contd.)
• An example to work with TreeMap:
import java.util.*;
class TestCollection{
public static void main(String args[]){
TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
hm.put(100,"Amay");
hm.put(101,"Viji");
hm.put(102,"Raj");

for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
TreeMap Class (Contd.)
• The preceding code output will be:
100 Amay
101 Viji
102 Raj
Collections Class
• Collections class consists exclusively of static methods that operate on
collections or return collections.
• The following table lists the methods in Collections class:
Method Description
public static <T> void sort(List<T> list, Sorts the specified list according to the order
Comparator<? super T> c) induced by the specified comparator.
public static <T> int Searches the specified list for the specified
binarySearch(List<? extends object using the binary search algorithm.
Comparable<? super T>> list,
T key)
Arrays Class
• The Arrays class contains various methods for manipulating arrays.
• The following table lists the methods available in Arrays class:
Method Description
public static void sort(Object[] a, Sorts the specified range of the specified
int fromIndex, array of objects into ascending order,
int toIndex) according to the natural ordering of its
elements.
public static int binarySearch(int[] a, Searches the specified array of ints for the
int key) specified value using the binary search
algorithm.
Sorting Elements in Collection
• An example to sort the elements in ArrayList:
import java.util.*;
class TestCollection{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Rajiv");
al.add("Viji");
al.add("Rajiv");
al.add("Jay");
Sorting Elements in Collection (Contd.)
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
Collections.sort(al);
System.out.println(al);
}
}
• The preceding code output will be:
Rajiv
Viji
Rajiv
Jay
[Jay, Rajiv, Rajiv, Viji]
Sorting Elements in Array (Contd.)
• An example to sort the elements in an array:
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
int iArr[] = {2, 1, 9, 6, 4};
for (int number : iArr) {
System.out.println("Number = " + number);
}
Arrays.sort(iArr);
System.out.println("The sorted array is:");
for (int number : iArr) {
System.out.println("Number = " + number);
}
}
}
Sorting Elements in Array (Contd.)
• The preceding code output will be:
Number = 2
Number = 1
Number = 9
Number = 6
Number = 4
The sorted array is:
Number = 1
Number = 2
Number = 4
Number = 6
Number = 9
Searching an Element in Collection
• An example to sort the elements in ArrayList:
import java.util.*;
class TestCollection{
public static void main(String args[]) {
ArrayList<String> arlst=new ArrayList<String>();
arlst.add("TP");
arlst.add("PROVIDES");
arlst.add("QUALITY");
arlst.add("TUTORIALS");
int index=Collections.binarySearch(arlst, "QUALITY");
System.out.println("'QUALITY' is available at index:
"+index);
}
}
Searching an Element in Collection (Contd.)
• The preceding code output will be:
'QUALITY' is available at index: 2
Searching an Element in Array
• An example to search an element in an array:
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
int intArr[] = {30,20,5,12,55};
int searchVal = 12;
int retVal = Arrays.binarySearch(intArr,searchVal);
System.out.println("The index of element 12 is : "
+ retVal);
}
}
Searching an Element in Array (Contd.)
• The preceding code output will be:
The index of element 12 is : 3
Vector Class
• The Vector implements List Interface.
• The Vector collections maintains insertion order.
• Vector collection is synchronized.
• The following table list the methods in Vector class:
Method Description
public void addElement(E obj) Adds the specified component to the end of this
vector, increasing its size by one.
public boolean remove(Object o) Removes the first occurrence of the specified
element in this Vector
public int size() Returns the number of components in this
vector.
public boolean isEmpty() Tests if this vector has no components.
Vector Class (Contd.)
• An example to work with Vector class:
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
Vector<String> vec = new Vector<String>(2);
vec.addElement("Apple");
vec.addElement("Orange");
vec.addElement("Mango");
System.out.println("Size is: "+vec.size());
Vector Class (Contd.)
vec.addElement("Fig");
System.out.println("Size after addition:
"+vec.size());
vec.removeElement("Apple");
System.out.println("Size after deletion:
"+vec.size());
System.out.println(vec);
}
}
• The preceding code output will be:
Size is: 3
Size after addition: 4
Size after deletion: 3
[Orange, Mango, Fig]
HashTable Class
• A HashTable collection is an array of list.
• Each list is known as a bucket.
• The position of bucket is identified by calling the hashcode() method.
• A HashTable collection contains values based on the key.
• The HashTable class implements the Map interface and extends
Dictionary class.
• A HashTable collection contains only unique elements.
• A HashTable collection may have not have any null key or value.
• A HashTable collection is synchronized.
HashTable Class (Contd.)
• The following table lists the methods in HashTable class:
Method Description
public V put(K key, Maps the specified key to the
V value) specified value in this hashtable.
public Set<Map.Entry<K,V>> entrySet() Returns a Set view of the mappings
contained in this map.
public V remove(Object key) Removes the key (and its corresponding
value) from this hashtable.
public int size() Returns the number of keys in this
hashtable.
public boolean isEmpty() Tests if this hashtable maps no keys to
values.
HashTable Class (Contd.)
• An example to work with HashTable:
import java.util.*;
class TestCollection{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
HashTable Class (Contd.)
• The preceding code output will be:
103 Rahul
102 Ravi
101 Vijay
100 Amit
Enumeration Interface
• The Enumeration interface defines the methods by which you can
enumerate the elements in a collection of objects.
• The following table lists the methods in Enumeration interface:

Method Description
boolean hasMoreElements( Return true while there are still more elements to
) extract, and false when all the elements have been
enumerated.
Object nextElement( ) Returns the next object in the enumeration as a generic
Object reference.
Enumeration Interface
• An example to work with Enumeration interface:
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
Enumeration Interface (Contd.)
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements()){
System.out.println(days.nextElement());
}
}
}
Enumeration Interface (Contd.)
• The preceding code output will be:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Comparable Interface
• Comparable interface is used to sort the objects of user-defined class.
• When the elements in a list needs to be sorted according to their
natural order, Comparable interface must be used.
• While working with Comparable interface, the class whose objects to
be sorted must implement this interface
• The public int compareTo(Object obj) method is used to compare the
current object with the specified object.
Comparable Interface
• An example to work with Comparable interface:
class Student implements Comparable{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
Comparable Interface (Contd.)
public int compareTo(Object obj){
Student st=(Student)obj;
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}
Comparable Interface (Contd.)
import java.util.*;
import java.io.*;
class TestComparable{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
Collections.sort(al);
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+“ "+st.age);
}
}
}
Comparable Interface (Contd.)
• The preceding code output will be:
105 Jai 21
101 Vijay 23
106 Ajay 27
Comparator Interface
• The Comparator interface is used to sort the objects of user-defined
class.
• While working with Comparator interface, the class whose objects to
be sorted does implement this interface.
• The public int compare(Object obj1,Object obj2) method compares
the first object with second object.
Comparator Interface (Contd.)
• An example to work with Comparator interface:
public class Country{
int countryId;
String countryName;

public Country(int countryId, String countryName) {


super();
this.countryId = countryId;
this.countryName = countryName;
}

public int getCountryId() {


return countryId;
}
Comparator Interface (Contd.)
public void setCountryId(int countryId) {
this.countryId = countryId;
}

public String getCountryName() {


return countryName;
}

public void setCountryName(String countryName) {


this.countryName = countryName;
}

}
Comparator Interface (Contd.)

import java.util.Comparator;

public class CountrySortByIdComparator implements


Comparator<Country>{
public int compare(Country country1, Country country2)
{
return (country1.getCountryId() <
country2.getCountryId() ) ? -1: (country1.getCountryId() >
country2.getCountryId() ) ? 1:0 ;
}

}
Comparator Interface (Contd.)
import java.util.*;
public class ComparatorMain{
public static void main(String[] args) {
Country indiaCountry=new Country(1, "India");
Country chinaCountry=new Country(4, "China");
Country nepalCountry=new Country(3, "Nepal");
Country bhutanCountry=new Country(2,
"Bhutan");
List<Country> listOfCountries = new
ArrayList<Country>();
Comparator Interface (Contd.)
listOfCountries.add(indiaCountry);
listOfCountries.add(chinaCountry);
listOfCountries.add(nepalCountry);
listOfCountries.add(bhutanCountry);
System.out.println("Before Sort by id : ");
for (int i = 0; i < listOfCountries.size();
i++) {
Country country=(Country)
listOfCountries.get(i);
System.out.println("Country Id:
"+country.getCountryId()+"||"+"Country name:
"+country.getCountryName());
}
Comparator Interface (Contd.)
Collections.sort(listOfCountries,new CountrySortByIdComparator());
System.out.println("After Sort by id: ");
for (int i = 0; i < listOfCountries.size(); i++) {
Country country=(Country)
listOfCountries.get(i);
System.out.println("Country Id:
"+country.getCountryId()+"|| "+"Country name:
"+country.getCountryName());
}
Collections.sort(listOfCountries,new
Comparator<Country>() {
public int compare(Country o1, Country o2) {
return
o1.getCountryName().compareTo(o2.getCountryName());
}
});
Comparator Interface (Contd.)
System.out.println("After Sort by name: ");
for (int i = 0; i < listOfCountries.size();
i++) {
Country country=(Country)
listOfCountries.get(i);
System.out.println("Country Id:
"+country.getCountryId()+"|| "+"Country name:
"+country.getCountryName());
}
}

}
Comparator Interface (Contd.)
• The preceding code output will be:
Before Sort by id :
Country Id: 1||Country name: India
Country Id: 4||Country name: China
Country Id: 3||Country name: Nepal
Country Id: 2||Country name: Bhutan
After Sort by id:
Country Id: 1|| Country name: India
Country Id: 2|| Country name: Bhutan
Country Id: 3|| Country name: Nepal
Country Id: 4|| Country name: China
After Sort by name:
Country Id: 2|| Country name: Bhutan
Country Id: 4|| Country name: China
Country Id: 1|| Country name: India
Country Id: 3|| Country name: Nepal
Summary
• In this topic, you learnt that:
• To work with date, Java provides classes, such as Date, Calendar, DateFormat, and
Locale.
• Generic in Java provides compile time type-safety of code and removing risk
of ClassCastException.
• The collections in java is a framework that provides an architecture to store and
manipulate the group of objects.
• The Collection interface is used to pass around collections of objects where
maximum generality is desired.
• Iterator interface provides the facility of iterating the elements in forward direction
only.
• ListIterator Interface is used to traverse the element in backward and forward
direction.
• A List is an ordered Collection and can contain duplicate elements.
Summary
• A Set is a collection that cannot contain duplicate elements.
• A Map collection contains values based on the key and value pair.
• Collections class consists exclusively of static methods that operate on
collections or return collections.
• The Arrays class contains various methods for manipulating arrays.
• Vector and HashTable collections are synchronized.
• The Enumeration interface defines the methods by which you can enumerate
the elements in a collection of objects.
• Comparable and Comparator interfaces are used to sort the objects of user-
defined class.

You might also like