0% found this document useful (0 votes)
16 views

Collections in Java

Uploaded by

mail2sgupta1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Collections in Java

Uploaded by

mail2sgupta1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Collections in Java

1. Java Collection Framework


2. Hierarchy of Collection Framework
3. Collection interface
4. Iterator interface

Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.

All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSetetc).

What is Collection in java

Collection represents a single unit of objects i.e. a group.

What is framework in java

• provides readymade architecture.


• represents set of classes and interface.
• is optional.

What is Collection framework

Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:

1. Interfaces and its implementations i.e. classes


2. Algorithm

Do You Know ?

• What are the two ways to iterate the elements of a collection ?


• What is the difference between ArrayList and LinkedList classes in collection
framework?
• What is the difference between ArrayList and Vector classes in collection framework?
• What is the difference between HashSet and HashMap classes in collection
framework?
• What is the difference between HashMap and Hashtable class?
• What is the difference between Iterator and Enumeration interface in collection
framework?
• How can we sort the elements of an object. What is the difference between
Comparable and Comparator interfaces?
• What does the hashcode() method ?

li>What is the difference between java collection and java collections ?

Hierarchy of Collection Framework

Let us see the hierarchy of collection framework.Thejava.util package contains all the classes
and interfaces for Collection framework.

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No. Method Description


public boolean add(Object
1 is used to insert an element in this collection.
element)
is used to insert the specified collection elements in
2 public booleanaddAll(collection c)
the invoking collection.
public boolean remove(Object
3
element)
public is used to delete all the elements of specified
4
booleanremoveAll(Collection c) collection from the invoking collection.
public booleanretainAll(Collection is used to delete all the elements of invoking
5
c) collection except the specified collection.
return the total number of elements in the
6 public int size()
collection.
7 public void clear() removes the total no of element from the collection.
public boolean contains(object
8 is used to search an element.
element)
public is used to search the specified collection in this
9
booleancontainsAll(Collection c) collection.
10 public Iterator iterator() returns an iterator.
11 public Object[] toArray() converts collection into array.
12 public booleanisEmpty() checks if collection is empty.
public boolean equals(Object
13 matches two collection.
element)
14 public inthashCode() returns the hashcode number for collection.

Iterator interface

Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

1. publicbooleanhasNext() it returns true if iterator has more elements.


2. public object next() it returns the element and moves the cursor pointer to the next
element.
3. public void remove() it removes the last elements returned by the iterator. It is rarely
used.

What we are going to learn in Java Collections Framework

1. ArrayList class
2. LinkedList class
3. ListIterator interface
4. HashSet class
5. LinkedHashSet class
6. TreeSet class
7. PriorityQueue class
8. Map interface
9. HashMap class
10. LinkedHashMap class
11. TreeMap class
12. Hashtable class
13. Sorting
14. Comparable interface
15. Comparator interface
16. Properties class in Java

Next TopicArrayListIn Collection Framework

Java ArrayList class


• Java ArrayList class uses a dynamic array for storing the elements.It 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.

Java Non-generic Vs Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

Java new generic collection allows you to have only one type of object in collection. Now it
is type safe so typecasting is not required at run time.

Let's see the old non-generic example of creating java collection.

1. ArrayList al=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

1. ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist

In generic collection, we specify the type in angular braces. Now ArrayList is forced to have
only specified type of objects in it. If you try to add another type of object, it gives compile
time error.

For more information of java generics, click here Java Generics Tutorial.

Example of Java ArrayList class


1. import java.util.*;
2. class TestCollection1{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();//creating arraylist
6. al.add("Ravi");//adding object in arraylist
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Test it Now
Ravi
Vijay
Ravi
Ajay

Two ways to iterate the elements of collection in java

1. By Iterator interface.
2. By for-each loop.

In the above example, we have seen traversing ArrayList by Iterator. Let's see the example to
traverse ArrayList elements using for-each loop.

Iterating the elements of Collection by for-each loop

1. import java.util.*;
2. class TestCollection2{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. for(String obj:al)
10. System.out.println(obj);
11. }
12. }

Test it Now
Ravi
Vijay
Ravi
Ajay
User-defined class objects in Java ArrayList

1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }

1. import java.util.*;
2. public class TestCollection3{
3. public static void main(String args[]){
4. //Creating user-defined class objects
5. Student s1=new Student(101,"Sonoo",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8.
9. ArrayList<Student> al=new ArrayList<Student>();//creating arraylist
10. al.add(s1);//adding Student class object
11. al.add(s2);
12. al.add(s3);
13.
14. Iterator itr=al.iterator();
15. //traversing elements of ArrayList object
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20. }
21. }

Test it Now
101 Sonoo 23
102 Ravi 21
103 Hanumat 25

Example of addAll(Collection c) method

1. import java.util.*;
2. class TestCollection4{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ajay");
9.
10. ArrayList<String> al2=new ArrayList<String>();
11. al2.add("Sonoo");
12. al2.add("Hanumat");
13.
14. al.addAll(al2);
15.
16. Iterator itr=al.iterator();
17. while(itr.hasNext()){
18. System.out.println(itr.next());
19. }
20. }
21. }

Test it Now
Ravi
Vijay
Ajay
Sonoo
Hanumat

Example of removeAll() method

1. import java.util.*;
2. class TestCollection5{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ajay");
9.
10. ArrayList<String> al2=new ArrayList<String>();
11. al2.add("Ravi");
12. al2.add("Hanumat");
13.
14. al.removeAll(al2);
15.
16. System.out.println("iterating the elements after removing the elements of al2...");
17. Iterator itr=al.iterator();
18. while(itr.hasNext()){
19. System.out.println(itr.next());
20. }
21.
22. }
23. }
Test it Now
iterating the elements after removing the elements of al2...
Vijay
Ajay

Example of retainAll() method

1. import java.util.*;
2. class TestCollection6{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11.
12. al.retainAll(al2);
13.
14. System.out.println("iterating the elements after retaining the elements of al2...");
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. System.out.println(itr.next());
18. }
19. }
20. }

Test it Now
iterating the elements after retaining the elements of al2...
Ravi
Next TopicLinkedListIn Collection Framework

Java 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.
Java LinkedList Example

1. import java.util.*;
2. public class TestCollection7{
3. public static void main(String args[]){
4.
5. LinkedList<String> al=new LinkedList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Test it Now
Output:Ravi
Vijay
Ravi
Ajay
Next TopicArrayList vs LinkedList

Difference between ArrayList and


LinkedList
ArrayList and LinkedList both implements List interface and maintains insertion order. Both
are non synchronized classes.

But there are many differences between ArrayList and LinkedList classes that are given
below.

ArrayList LinkedList
1) ArrayList internally uses dynamic array to LinkedList internally uses doubly linked
store the elements. list to store the elements.
2) Manipulation with ArrayList is slow because Manipulation with LinkedList is faster
it internally uses array. If any element is than ArrayList because it uses doubly
removed from the array, all the bits are shifted linked list so no bit shifting is required in
in memory. memory.
LinkedList class can act as a list and
3) ArrayList class can act as a list only because
queue both because it implements List and
it implements List only.
Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for manipulating
accessing data. data.

Example of ArrayList and LinkedList in Java

Let's see a simple example where we are using ArrayList and LinkedList both.

1. import java.util.*;
2. class TestArrayLinked{
3. public static void main(String args[]){
4.
5. List<String> al=new ArrayList<String>();//creating arraylist
6. al.add("Ravi");//adding object in arraylist
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. List<String> al2=new LinkedList<String>();//creating linkedlist
12. al2.add("James");//adding object in linkedlist
13. al2.add("Serena");
14. al2.add("Swati");
15. al2.add("Junaid");
16.
17. System.out.println("arraylist: "+al);
18. System.out.println("linkedlist: "+al2);
19. }
20. }

Test it Now

Output:

arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]
Next TopicListIterator in Java Collection

Java List Interface


List Interface is the subinterface of Collection.It contains methods to insert and delete
elements in index basis.It is a factory of ListIterator interface.

Commonly used methods of List Interface:


1. public void add(intindex,Object element);
2. public booleanaddAll(intindex,Collection c);
3. public object get(int Index position);
4. public object set(intindex,Object element);
5. public object remove(int index);
6. public ListIteratorlistIterator();
7. public ListIteratorlistIterator(inti);

Java ListIterator Interface

ListIterator Interface is used to traverse the element in backward and forward direction.

Commonly used methods of ListIterator Interface:

1. public booleanhasNext();
2. public Object next();
3. public booleanhasPrevious();
4. public Object previous();

Example of ListIterator Interface:

1. import java.util.*;
2. public class TestCollection8{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Amit");
7. al.add("Vijay");
8. al.add("Kumar");
9. al.add(1,"Sachin");
10.
11. System.out.println("element at 2nd position: "+al.get(2));
12.
13. ListIterator<String> itr=al.listIterator();
14.
15. System.out.println("traversing elements in forward direction...");
16. while(itr.hasNext()){
17. System.out.println(itr.next());
18. }
19.
20.
21. System.out.println("traversing elements in backward direction...");
22. while(itr.hasPrevious()){
23. System.out.println(itr.previous());
24. }
25. }
26. }

Test it Now
Output:element at 2nd position: Vijay
traversing elements in forward direction...
Amit
Sachin
Vijay
Kumar
traversing elements in backward direction...
Kumar
Vijay
Sachin
Amit
Next TopicHashSet Class In Collection Framework

Java HashSet class


• useshashtable to store the elements.It extends AbstractSet class and implements Set
interface.
• contains unique elements only.

Difference between List and Set:

List can contain duplicate elements whereas Set contains unique elements only.

Hierarchy of HashSet class:

Example of HashSet class:


1. import java.util.*;
2. class TestCollection9{
3. public static void main(String args[]){
4.
5. HashSet<String> al=new HashSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Test it Now
Output:Ajay
Vijay
Ravi
Next TopicLinkedHashSet Class In Collection Framework

Java TreeSet class


• contains unique elements only like HashSet. The TreeSet class implements NavigableSet
interface that extends the SortedSet interface.
• maintains ascending order.
Hierarchy of TreeSet class:

Example of TreeSet class:

1. import java.util.*;
2. class TestCollection11{
3. public static void main(String args[]){
4.
5. TreeSet<String> al=new TreeSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Test it Now
Output:Ajay
Ravi
Vijay

Next TopicPriorityQueue Class In Collection Framework

Java LinkedHashSet class:


• contains unique elements only like HashSet. It extends HashSet class and implements Set
interface.
• maintains insertion order.

Hierarchy of LinkedHashSet class:

Example of LinkedHashSet class:

1. import java.util.*;
2. class TestCollection10{
3. public static void main(String args[]){
4.
5. LinkedHashSet<String> al=new LinkedHashSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Test it Now
Output:>Ravi
Vijay
Ajay

Next TopicTreeSet Class In Collection Framework


<<prevnext>>

Java Queue Interface


The Queue interface basically orders the element in FIFO(First In First Out)manner.

Methods of Queue Interface :

1. public boolean add(object);


2. public boolean offer(object);
3. public remove();
4. public poll();
5. public element();
6. public peek();

PriorityQueue class:

The PriorityQueue class provides the facility of using queue. But it does not orders the
elements in FIFO manner.

Example of PriorityQueue:

1. import java.util.*;
2. class TestCollection12{
3. public static void main(String args[]){
4.
5. PriorityQueue<String> queue=new PriorityQueue<String>();
6. queue.add("Amit");
7. queue.add("Vijay");
8. queue.add("Karan");
9. queue.add("Jai");
10. queue.add("Rahul");
11.
12. System.out.println("head:"+queue.element());
13. System.out.println("head:"+queue.peek());
14.
15. System.out.println("iterating the queue elements:");
16. Iterator itr=queue.iterator();
17. while(itr.hasNext()){
18. System.out.println(itr.next());
19. }
20.
21. queue.remove();
22. queue.poll();
23.
24. System.out.println("after removing two elements:");
25. Iterator<String> itr2=queue.iterator();
26. while(itr2.hasNext()){
27. System.out.println(itr2.next());
28. }
29.
30. }
31. }

Test it Now
Output:head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay

Next TopicMap interface


<<prevnext>>
Java Map Interface
A map contains values based on the key i.e. key and value pair.Each pair is known as an
entry.Map contains only unique elements.

Commonly used methods of Map interface:

1. public Object put(object key,Object value): is used to insert an entry in this map.
2. public void putAll(Map map):is used to insert the specified map in this map.
3. public Object remove(object key):is used to delete an entry for the specified key.
4. public Object get(Object key):is used to return the value for the specified key.
5. publicbooleancontainsKey(Object key):is used to search the specified key from this
map.
6. publicbooleancontainsValue(Object value):is used to search the specified value
from this map.
7. public Set keySet():returns the Set view containing all the keys.
8. public Set entrySet():returns the Set view containing all the keys and values.

Entry

Entry is the subinterface of Map.So we will access it by Map.Entryname.It provides methods


to get key and value.

Methods of Entry interface:

1. public Object getKey(): is used to obtain key.


2. public Object getValue():is used to obtain value.

Next TopicHashMap Class In Collection Framework

Java HashMap class


• A HashMap contains values based on the key. It implements the Map interface and extends
AbstractMap class.
• It contains only unique elements.
• It may have one null key and multiple null values.
• It maintains no order.
Hierarchy of HashMap class:

Example of HashMap class:

1. import java.util.*;
2. class TestCollection13{
3. public static void main(String args[]){
4.
5. HashMap<Integer,String> hm=new HashMap<Integer,String>();
6.
7. hm.put(100,"Amit");
8. hm.put(101,"Vijay");
9. hm.put(102,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }

Test it Now
Output:102 Rahul
100 Amit
101 Vijay

What is difference between HashSet and HashMap?

HashSet contains only values whereas HashMap contains entry(key and value).

Next TopicLinkedHashMap Class In Collection Framework

Java LinkedHashMap class


• A LinkedHashMap contains values based on the key. It implements the Map interface and
extends HashMap class.
• It contains only unique elements.
• It may have one null key and multiple null values.
• It is same as HashMap instead maintains insertion order.

Hierarchy of LinkedHashMap class:

Example of LinkedHashMap class:

1. import java.util.*;
2. class TestCollection14{
3. public static void main(String args[]){
4.
5. LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
6.
7. hm.put(100,"Amit");
8. hm.put(101,"Vijay");
9. hm.put(102,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }

Test it Now
Output:100 Amit
101 Vijay
103 Rahul
Next TopicTreeMap Class In Collection Framework
Java TreeMap class
• A TreeMap contains values based on the key. It implements the NavigableMap interface and
extends AbstractMap class.
• It contains only unique elements.
• It cannot have null key but can have multiple null values.
• It is same as HashMap instead maintains ascending order.

Hierarchy of TreeMap class:

Example of TreeMap class:

1. import java.util.*;
2. class TestCollection15{
3. public static void main(String args[]){
4.
5. TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
6.
7. hm.put(100,"Amit");
8. hm.put(102,"Ravi");
9. hm.put(101,"Vijay");
10. hm.put(103,"Rahul");
11.
12. for(Map.Entry m:hm.entrySet()){
13. System.out.println(m.getKey()+" "+m.getValue());
14. }
15. }
16. }

Test it Now
Output:100 Amit
101 Vijay
102 Ravi
103 Rahul

What is difference between HashMap and TreeMap?

1) HashMap is can contain one null key. TreeMap can not contain any null key.

2) HashMap maintains no order. TreeMap maintains ascending order.

Next TopicHashtable Class In Collection Framework

Java Hashtable class


• A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is
identified by calling the hashcode() method.AHashtable contains values based on the
key. It implements the Map interface and extends Dictionary class.
• It contains only unique elements.
• It may have not have any null key or value.
• It is synchronized.

Example of Hashtable:

1. import java.util.*;
2. class TestCollection16{
3. public static void main(String args[]){
4.
5. Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
6.
7. hm.put(100,"Amit");
8. hm.put(102,"Ravi");
9. hm.put(101,"Vijay");
10. hm.put(103,"Rahul");
11.
12. for(Map.Entry m:hm.entrySet()){
13. System.out.println(m.getKey()+" "+m.getValue());
14. }
15. }
16. }

Test it Now
Output:103 Rahul
102 Ravi
101 Vijay
100 Amit

Next TopicDifference between HashMap and Hashtable


Difference between HashMap and
Hashtable
HashMap and Hashtable both are used to store data in key and value form. Both are using
hashing technique to store unique keys.

But there are many differences between HashMap and Hashtable classes that are given
below.

HashMap Hashtable

1) HashMap is non synchronized. It is not-thread safe and can't Hashtable is synchronized. It is


be shared between many threads without proper thread-safe and can be shared
synchronization code. with many threads.

Hashtabledoesn't allow any null


2) HashMapallows one null key and multiple null values.
key or value.

3) HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class.

4) HashMap is fast. Hashtable is slow.

5) We can make the HashMap as synchronized by calling this Hashtable is internally


code synchronized and can't be
Map m = Collections.synchronizedMap(hashMap); unsynchronized.

Hashtable is traversed by
6) HashMap is traversed by Iterator.
Enumerator and Iterator.

Enumerator in Hashtable is not


7) Iterator in HashMap is fail-fast.
fail-fast.

Hashtable inherits Dictionary


8) HashMap inherits AbstractMap class.
class.

Next TopicSorting in Java Collection

← prevnext →

Sorting
We can sort the elements of:

1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class provides static methods for sorting the elements of collection.If collection
elements are of Set type, we can use TreeSet.But We cannot sort the elements of
List.Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements

public void sort(List list): is used to sort the elements of List.List elements must be of
Comparable type.

Note: String class and Wrapper classes implements the Comparable interface.So if you
store the objects of string or wrapper classes, it will be Comparable.

Example of Sorting the elements of List that contains string objects

1. import java.util.*;
2. class TestSort1{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Viru");
7. al.add("Saurav");
8. al.add("Mukesh");
9. al.add("Tahir");
10.
11. Collections.sort(al);
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }

Test it Now
Output:Mukesh
Saurav
Tahir
Viru

Example of Sorting the elements of List that contains Wrapper class objects

1. import java.util.*;
2. class TestSort2{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add(Integer.valueOf(201));
7. al.add(Integer.valueOf(101));
8. al.add(230);//internally will be converted into objects as Integer.valueOf(230)
9.
10. Collections.sort(al);
11.
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }

Test it Now
Output:101
201
230

Next TopicComparable Interface In Collection Framework

Comparable interface
Comparable interface is used to order the objects of user-defined class.This interface is found
in java.lang package and contains only one method named compareTo(Object).It provide
only single sorting sequence i.e. you can sort the elements on based on single
datamemberonly.For instance it may be either rollno,name,age or anything else.

Syntax:

publicintcompareTo(Object obj): is used to compare the current object with the specified
object.

We can sort the elements of:

1. String objects
2. Wrapper class objects
3. User-defined class objects

Collections class provides static methods for sorting the elements of collection.If collection
elements are of Set type, we can use TreeSet.But We cannot sort the elements of
List.Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements

public void sort(List list): is used to sort the elements of List.List elements must be of
Comparable type.

Note: String class and Wrapper classes implements the Comparable interface.So if you
store the objects of string or wrapper classes, it will be Comparable.
Example of Sorting the elements of List that contains user-defined class objects on age
basis

Student.java

1. class Student implements Comparable{


2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10.
11. public int compareTo(Object obj){
12. Student st=(Student)obj;
13. if(age==st.age)
14. return 0;
15. else if(age>st.age)
16. return 1;
17. else
18. return -1;
19. }
20.
21. }

Simple.java

1. import java.util.*;
2. import java.io.*;
3.
4. class TestSort3{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.
12. Collections.sort(al);
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. Student st=(Student)itr.next();
16. System.out.println(st.rollno+""+st.name+""+st.age);
17. }
18. }
19. }

Test it Now
Output:105 Jai 21
101 Vijay 23
106 Ajay 27
Next TopicComparator Interface In Collection Framework

Comparator interface
Comparator interface is used to order the objects of user-defined class.

This interface is found in java.util package and contains 2 methods compare(Object


obj1,Object obj2) and equals(Object element).

It provides multiple sorting sequence i.e. you can sort the elements based on any data
member. For instance it may be on rollno, name, age or anything else.

Syntax of compare method

publicint compare(Object obj1,Object obj2): compares the first object with second object.

Collections class provides static methods for sorting the elements of collection. If collection
elements are of Set type, we can use TreeSet. But We cannot sort the elements of List.
Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements

public void sort(List list,Comparator c): is used to sort the elements of List by the given
comparator.

Example of sorting the elements of List that contains user-defined class


objects on the basis of age and name

In this example, we have created 4 java classes:

1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java

Student.java

This class contains three fieldsrollno, name and age and a parameterized constructor.

1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }

AgeComparator.java

This class defines comparison logic based on the age. If age of first object is greater than the
second, we are returning positive value, it can be any one such as 1, 2 , 10 etc. If age of first
object is less than the second object, we are returning negative value, it can be any negative
value and if age of both objects are equal, we are returning 0.

1. import java.util.*;
2. class AgeComparator implements Comparator{
3. public int Compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. if(s1.age==s2.age)
8. return 0;
9. else if(s1.age>s2.age)
10. return 1;
11. else
12. return -1;
13. }
14. }

NameComparator.java

This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.

1. import java.util.*;
2. class NameComparator implements Comparator{
3. public int Compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. return s1.name.compareTo(s2.name);
8. }
9. }

Simple.java

In this class, we are printing the objects values by sorting on the basis of name and age.

1. import java.util.*;
2. import java.io.*;
3.
4. class Simple{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.
12. System.out.println("Sorting by Name...");
13.
14. Collections.sort(al,new NameComparator());
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20.
21. System.out.println("sorting by age...");
22.
23. Collections.sort(al,new AgeComparator());
24. Iterator itr2=al.iterator();
25. while(itr2.hasNext()){
26. Student st=(Student)itr2.next();
27. System.out.println(st.rollno+" "+st.name+" "+st.age);
28. }
29.
30.
31. }
32. }

Output:Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27
Next Topicproperties Class In Java

Properties class in Java


The properties object contains key and value pair both as a string. It is the subclass of
Hashtable.

It can be used to get property value based on the property key. The Properties class provides
methods to get data from properties file and store data into properties file. Moreover, it can be
used to get properties of system.
Advantage of properties file

Easy Maintenance: If any information is changed from the properties file, you don't need to
recompile the java class. It is mainly used to contain variable information i.e. to be changed.

Methods of Properties class

The commonly used methods of Properties class are given below.

Method Description
public void load(Reader r) loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream object
public String getProperty(String key) returns value based on the key.
public void setProperty(String key,String
sets the property in the properties object.
value)
public void store(Writer w, String comment) writers the properties in the writer object.
public void store(OutputStreamos, String writes the properties in the OutputStream
comment) object.
storeToXML(OutputStreamos, String writers the properties in the writer object for
comment) generating xml document.
writers the properties in the writer object for
public void storeToXML(Writer w, String
generating xml document with specified
comment, String encoding)
encoding.

Example of Properties class to get information from properties file

To get information from the properties file, create the properties file first.

db.properties

1. user=system
2. password=oracle

Now, lets create the java class to read the data from the properties file.

Test.java

1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5. FileReader reader=new FileReader("db.properties");
6.
7. Properties p=new Properties();
8. p.load(reader);
9.
10. System.out.println(p.getProperty("user"));
11. System.out.println(p.getProperty("password"));
12. }
13. }

Output:system
oracle

Now if you change the value of the properties file, you don't need to compile the java class
again. That means no maintenance problem.

Example of Properties class to get all the system properties

By System.getProperties() method we can get all the properties of system. Let's create the
class that gets information from the system properties.

Test.java

1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=System.getProperties();
7. Set set=p.entrySet();
8.
9. Iterator itr=set.iterator();
10. while(itr.hasNext()){
11. Map.Entry entry=(Map.Entry)itr.next();
12. System.out.println(entry.getKey()+" = "+entry.getValue());
13. }
14.
15. }
16. }

Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator= ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
...........

Example of Properties class to create properties file


Now lets write the code to create the properties file.

Test.java

1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=new Properties();
7. p.setProperty("name","Sonoo Jaiswal");
8. p.setProperty("email","[email protected]");
9.
10. p.store(new FileWriter("info.properties"),"Javatpoint Properties Example");
11.
12. }
13. }

Let's see the generated properties file.

info.properties

1. #Javatpoint Properties Example


2. #Thu Oct 03 22:35:53 IST 2013
3. [email protected]
4. name=Sonoo Jaiswal

Next TopicArrayList vs Vector

Difference between ArrayList and Vector


ArrayList and Vector both implements List interface and maintains insertion order.

But there are many differences between ArrayList and Vector classes that are given below.

ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
2) ArrayListincrements 50% of Vector increments 100% means doubles the array
current array size if number of size if total number of element exceeds than its
element exceeds from its capacity. capacity.
3) ArrayList is not a legacy class, it is
Vector is a legacy class.
introduced in JDK 1.2.
Vector is slow because it is synchronized i.e. in
4) ArrayList is fast because it is non- multithreading environment, it will hold the other
synchronized. threads in runnable or non-runnable state until
current thread releases the lock of object.
5) ArrayList uses Iterator interface to Vector uses Enumeration interface to traverse the
traverse the elements. elements. But it can use Iterator also.
Example of Java ArrayList

Let's see a simple example where we are using ArrayList to store and traverse the elements.

1. import java.util.*;
2. class TestArrayList21{
3. public static void main(String args[]){
4.
5. List<String> al=new ArrayList<String>();//creating arraylist
6. al.add("Sonoo");//adding object in arraylist
7. al.add("Michael");
8. al.add("James");
9. al.add("Andy");
10. //traversing elements using Iterator
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Test it Now

Output:

Sonoo
Michael
James
Andy

Example of Java Vector

Let's see a simple example of java Vector class that uses Enumeration interface.

1. import java.util.*;
2. class TestVector1{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();//creating vector
5. v.add("umesh");//method of Collection
6. v.addElement("irfan");//method of Vector
7. v.addElement("kumar");
8. //traversing elements using Enumeration
9. Enumeration e=v.elements();
10. while(e.hasMoreElements()){
11. System.out.println(e.nextElement());
12. }
13. }
14. }

Test it Now
Output:

umesh
irfan
kumar
Next TopicCollections in Java

You might also like