0% found this document useful (0 votes)
7 views33 pages

Java Collections Framework Overview

The document provides an overview of the Java Collections Framework, which offers a structure for storing and manipulating groups of objects through various interfaces and classes. It details the Collection and Iterator interfaces, methods for adding, removing, and iterating elements, and differences between data structures like ArrayList and LinkedList. Additionally, it introduces concepts like generics in collections and examples of using different collection types.

Uploaded by

sauravguptaapr
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views33 pages

Java Collections Framework Overview

The document provides an overview of the Java Collections Framework, which offers a structure for storing and manipulating groups of objects through various interfaces and classes. It details the Collection and Iterator interfaces, methods for adding, removing, and iterating elements, and differences between data structures like ArrayList and LinkedList. Additionally, it introduces concepts like generics in collections and examples of using different collection types.

Uploaded by

sauravguptaapr
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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, TreeSet etc).

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 [Link] [Link] 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

1 public boolean add(Object element) is used to insert an element in this collection.


2 public boolean addAll(Collection c) is used to insert the specified collection elements in the invoking
collection.

3 public boolean remove(Object is used to delete an element from this collection.


element)

4 public boolean removeAll(Collection is used to delete all the elements of specified collection from the
c) invoking collection.

5 public boolean retainAll(Collection is used to delete all the elements of invoking collection except the
c) specified collection.

6 public int size() return the total number of elements in the collection.

7 public void clear() removes the total no of element from the collection.

8 public boolean contains(Object is used to search an element.


element)

9 public boolean is used to search the specified collection in this collection.


containsAll(Collection c)

10 public Iterator iterator() returns an iterator.

11 public Object[] toArray() converts collection into array.

12 public boolean isEmpty() checks if collection is empty.

13 public boolean equals(Object matches two collection.


element)

14 public int hashCode() 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. public boolean hasNext() 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

Java ArrayList class


o Java ArrayList class uses a dynamic array for storing the [Link] extends AbstractList class and
implements List interface.
o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o 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 [Link].*;
2. class TestCollection1{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();//creating arraylist
6. [Link]("Ravi");//adding object in arraylist
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10.
11. Iterator itr=[Link]();//getting Iterator from arraylist to traverse elements
12. while([Link]()){
13. [Link]([Link]());
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 [Link].*;
2. class TestCollection2{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. [Link]("Ravi");
6. [Link]("Vijay");
7. [Link]("Ravi");
8. [Link]("Ajay");
9. for(String obj:al)
10. [Link](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. [Link]=rollno;
7. [Link]=name;
8. [Link]=age;
9. }
10. }
1. import [Link].*;
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. [Link](s1);//adding Student class object
11. [Link](s2);
12. [Link](s3);
13.
14. Iterator itr=[Link]();
15. //traversing elements of ArrayList object
16. while([Link]()){
17. Student st=(Student)[Link]();
18. [Link]([Link]+" "+[Link]+" "+[Link]);
19. }
20. }
21. }
Test it Now
101 Sonoo 23
102 Ravi 21
103 Hanumat 25

Example of addAll(Collection c) method


1. import [Link].*;
2. class TestCollection4{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ajay");
9.
10. ArrayList<String> al2=new ArrayList<String>();
11. [Link]("Sonoo");
12. [Link]("Hanumat");
13.
14. [Link](al2);
15.
16. Iterator itr=[Link]();
17. while([Link]()){
18. [Link]([Link]());
19. }
20. }
21. }
Test it Now
Ravi
Vijay
Ajay
Sonoo
Hanumat

Example of removeAll() method


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

Example of retainAll() method


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

Java LinkedList class


o Java LinkedList class uses doubly linked list to store the elements. It extends the AbstractList class
and implements List and Deque interfaces.
o Java LinkedList class can contain duplicate elements.
o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
o Java LinkedList class can be used as list, stack or queue.

Java LinkedList Example


1. import [Link].*;
2. public class TestCollection7{
3. public static void main(String args[]){
4.
5. LinkedList<String> al=new LinkedList<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10.
11. Iterator<String> itr=[Link]();
12. while([Link]()){
13. [Link]([Link]());
14. }
15. }
16. }
Test it Now
Output:Ravi
Vijay
Ravi
Ajay

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 store the LinkedList internally uses doubly linked list to store
elements. the elements.

2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than ArrayList
internally uses array. If any element is removed from the because it uses doubly linked list so no bit shifting is
array, all the bits are shifted in memory. required in memory.

3) ArrayList class can act as a list only because it LinkedList class can act as a list and queue both
implements List only. because it implements List and Deque interfaces.

4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.

Example of ArrayList and LinkedList in Java


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

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

Output:

arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]

Java List Interface


List Interface is the subinterface of [Link] contains methods to insert and delete elements in index
[Link] is a factory of ListIterator interface.

Commonly used methods of List Interface:


1. public void add(int index,Object element);
2. public boolean addAll(int index,Collection c);
3. public object get(int Index position);
4. public object set(int index,Object element);
5. public object remove(int index);
6. public ListIterator listIterator();
7. public ListIterator listIterator(int i);

Java ListIterator Interface


ListIterator Interface is used to traverse the element in backward and forward direction.
Commonly used methods of ListIterator Interface:
1. public boolean hasNext();
2. public Object next();
3. public boolean hasPrevious();
4. public Object previous();

Example of ListIterator Interface:


1. import [Link].*;
2. public class TestCollection8{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. [Link]("Amit");
7. [Link]("Vijay");
8. [Link]("Kumar");
9. [Link](1,"Sachin");
10.
11. [Link]("element at 2nd position: "+[Link](2));
12.
13. ListIterator<String> itr=[Link]();
14.
15. [Link]("traversing elements in forward direction...");
16. while([Link]()){
17. [Link]([Link]());
18. }
19.
20.
21. [Link]("traversing elements in backward direction...");
22. while([Link]()){
23. [Link]([Link]());
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
Java HashSet class
o uses hashtable to store the [Link] extends AbstractSet class and implements Set interface.
o 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 [Link].*;
2. class TestCollection9{
3. public static void main(String args[]){
4.
5. HashSet<String> al=new HashSet<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10.
11. Iterator<String> itr=[Link]();
12. while([Link]()){
13. [Link]([Link]());
14. }
15. }
16. }
Test it Now

Output:Ajay
Vijay
Ravi

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 [Link].*;
2. class TestCollection10{
3. public static void main(String args[]){
4.
5. LinkedHashSet<String> al=new LinkedHashSet<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10.
11. Iterator<String> itr=[Link]();
12. while([Link]()){
13. [Link]([Link]());
14. }
15. }
16. }
Test it Now

Output:>Ravi
Vijay
Ajay

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 [Link].*;
2. class TestCollection11{
3. public static void main(String args[]){
4.
5. TreeSet<String> al=new TreeSet<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10.
11. Iterator<String> itr=[Link]();
12. while([Link]()){
13. [Link]([Link]());
14. }
15. }
16. }
Test it Now

Output:Ajay
Ravi
Vijay

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 [Link].*;
2. class TestCollection12{
3. public static void main(String args[]){
4.
5. PriorityQueue<String> queue=new PriorityQueue<String>();
6. [Link]("Amit");
7. [Link]("Vijay");
8. [Link]("Karan");
9. [Link]("Jai");
10. [Link]("Rahul");
11.
12. [Link]("head:"+[Link]());
13. [Link]("head:"+[Link]());
14.
15. [Link]("iterating the queue elements:");
16. Iterator itr=[Link]();
17. while([Link]()){
18. [Link]([Link]());
19. }
20.
21. [Link]();
22. [Link]();
23.
24. [Link]("after removing two elements:");
25. Iterator<String> itr2=[Link]();
26. while([Link]()){
27. [Link]([Link]());
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

Java Map Interface


A map contains values based on the key i.e. key and value [Link] pair is known as an [Link] 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. public boolean containsKey(Object key): is used to search the specified key from this map.
6. public boolean containsValue(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 be accessed it by [Link] name. 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.

Java HashMap class


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

Hierarchy of HashMap class:

Example of HashMap class:


1. import [Link].*;
2. class TestCollection13{
3. public static void main(String args[]){
4.
5. HashMap<Integer,String> hm=new HashMap<Integer,String>();
6.
7. [Link](100,"Amit");
8. [Link](101,"Vijay");
9. [Link](102,"Rahul");
10.
11. for([Link] m:[Link]()){
12. [Link]([Link]()+" "+[Link]());
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).

Java LinkedHashMap class


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

Hierarchy of LinkedHashMap class:

Example of LinkedHashMap class:


1. import [Link].*;
2. class TestCollection14{
3. public static void main(String args[]){
4.
5. LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
6.
7. [Link](100,"Amit");
8. [Link](101,"Vijay");
9. [Link](102,"Rahul");
10.
11. for([Link] m:[Link]()){
12. [Link]([Link]()+" "+[Link]());
13. }
14. }
15. }
Test it Now

Output:100 Amit
101 Vijay
103 Rahul

Java TreeMap class


o A TreeMap contains values based on the key. It implements the NavigableMap interface and extends
AbstractMap class.
o It contains only unique elements.
o It cannot have null key but can have multiple null values.
o It is same as HashMap instead maintains ascending order.

Hierarchy of TreeMap class:

Example of TreeMap class:


1. import [Link].*;
2. class TestCollection15{
3. public static void main(String args[]){
4.
5. TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
6.
7. [Link](100,"Amit");
8. [Link](102,"Ravi");
9. [Link](101,"Vijay");
10. [Link](103,"Rahul");
11.
12. for([Link] m:[Link]()){
13. [Link]([Link]()+" "+[Link]());
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.

Java Hashtable class


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

Example of Hashtable:
1. import [Link].*;
2. class TestCollection16{
3. public static void main(String args[]){
4.
5. Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
6.
7. [Link](100,"Amit");
8. [Link](102,"Ravi");
9. [Link](101,"Vijay");
10. [Link](103,"Rahul");
11.
12. for([Link] m:[Link]()){
13. [Link]([Link]()+" "+[Link]());
14. }
15. }
16. }
Test it Now
Output:103 Rahul
102 Ravi
101 Vijay
100 Amit

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 be Hashtable is synchronized. It is thread-
shared between many threads without proper synchronization code. safe and can be shared with many
threads.

2) HashMap allows one null key and multiple null values. Hashtable doesn't allow any null 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 code Hashtable is internally synchronized and
Map m = [Link](hashMap); can't be unsynchronized.

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


and Iterator.

7) Iterator in HashMap is fail-fast. Enumerator in Hashtable is not fail-fast.

8) HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.

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 [Link] collection elements are
of Set type, we can use [Link] We cannot sort the elements of [Link] 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 [Link] elements must be of Comparable
type.

Note: String class and Wrapper classes implements the Comparable [Link] 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 [Link].*;
2. class TestSort1{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. [Link]("Viru");
7. [Link]("Saurav");
8. [Link]("Mukesh");
9. [Link]("Tahir");
10.
11. [Link](al);
12. Iterator itr=[Link]();
13. while([Link]()){
14. [Link]([Link]());
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 [Link].*;
2. class TestSort2{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. [Link]([Link](201));
7. [Link]([Link](101));
8. [Link](230);//internally will be converted into objects as [Link](230)
9.
10. [Link](al);
11.
12. Iterator itr=[Link]();
13. while([Link]()){
14. [Link]([Link]());
15. }
16. }
17. }
Test it Now
Output:101
201
230

Comparable interface
Comparable interface is used to order the objects of user-defined [Link] interface is found in [Link]
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 datamember [Link] instance it may be either
rollno,name,age or anything else.

Syntax:

public int compareTo(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 [Link] collection elements are
of Set type, we can use [Link] We cannot sort the elements of [Link] 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 [Link] elements must be of Comparable
type.

Note: String class and Wrapper classes implements the Comparable [Link] 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

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

[Link]
1. import [Link].*;
2. import [Link].*;
3.
4. class TestSort3{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. [Link](new Student(101,"Vijay",23));
9. [Link](new Student(106,"Ajay",27));
10. [Link](new Student(105,"Jai",21));
11.
12. [Link](al);
13. Iterator itr=[Link]();
14. while([Link]()){
15. Student st=(Student)[Link]();
16. [Link]([Link]+""+[Link]+""+[Link]);
17. }
18. }
19. }
Test it Now
Output:105 Jai 21
101 Vijay 23
106 Ajay 27
Comparator interface
Comparator interface is used to order the objects of user-defined class.

This interface is found in [Link] 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

public int 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. [Link]
2. [Link]
3. [Link]
4. [Link]

[Link]

This class contains three fields rollno, 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. [Link]=rollno;
7. [Link]=name;
8. [Link]=age;
9. }
10. }
[Link]

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 [Link].*;
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([Link]==[Link])
8. return 0;
9. else if([Link]>[Link])
10. return 1;
11. else
12. return -1;
13. }
14. }
[Link]

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 [Link].*;
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 [Link]([Link]);
8. }
9. }
[Link]

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

1. import [Link].*;
2. import [Link].*;
3.
4. class Simple{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. [Link](new Student(101,"Vijay",23));
9. [Link](new Student(106,"Ajay",27));
10. [Link](new Student(105,"Jai",21));
11.
12. [Link]("Sorting by Name...");
13.
14. [Link](al,new NameComparator());
15. Iterator itr=[Link]();
16. while([Link]()){
17. Student st=(Student)[Link]();
18. [Link]([Link]+" "+[Link]+" "+[Link]);
19. }
20.
21. [Link]("sorting by age...");
22.
23. [Link](al,new AgeComparator());
24. Iterator itr2=[Link]();
25. while([Link]()){
26. Student st=(Student)[Link]();
27. [Link]([Link]+" "+[Link]+" "+[Link]);
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

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 value) sets the property in the properties object.

public void store(Writer w, String comment) writers the properties in the writer object.

public void store(OutputStream os, String writes the properties in the OutputStream object.
comment)

storeToXML(OutputStream os, String comment) writers the properties in the writer object for generating xml
document.

public void storeToXML(Writer w, String comment, writers the properties in the writer object for generating xml
String encoding) document with specified encoding.

Example of Properties class to get information from properties


file

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

[Link]
1. user=system
2. password=oracle

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

[Link]
1. import [Link].*;
2. import [Link].*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5. FileReader reader=new FileReader("[Link]");
6.
7. Properties p=new Properties();
8. [Link](reader);
9.
10. [Link]([Link]("user"));
11. [Link]([Link]("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 [Link]() method we can get all the properties of system. Let's create the class that gets
information from the system properties.

[Link]
1. import [Link].*;
2. import [Link].*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=[Link]();
7. Set set=[Link]();
8.
9. Iterator itr=[Link]();
10. while([Link]()){
11. [Link] entry=([Link])[Link]();
12. [Link]([Link]()+" = "+[Link]());
13. }
14.
15. }
16. }

Output:
[Link] = Java(TM) SE Runtime Environment
[Link] = C:\Program Files\Java\jdk1.7.0_01\jre\bin
[Link] = 21.1-b02
[Link] = Oracle Corporation
[Link] = [Link]
[Link] = ;
[Link] = Java HotSpot(TM) Client VM
[Link] = [Link]
[Link] = US
[Link] =
[Link] = SUN_STANDARD
...........

Example of Properties class to create properties file

Now lets write the code to create the properties file.

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

Let's see the generated properties file.

[Link]
1. #Javatpoint Properties Example
2. #Thu Oct 03 22:35:53 IST 2013
3. email=sonoojaiswal@[Link]
4. name=Sonoo Jaiswal

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) ArrayList increments 50% of current Vector increments 100% means doubles the array size if total
array size if number of element exceeds number of element exceeds than its capacity.
from its capacity.

3) ArrayList is not a legacy class, it is Vector is a legacy class.


introduced in JDK 1.2.

4) ArrayList is fast because it is non- Vector is slow because it is synchronized i.e. in multithreading
synchronized. environment, it will hold the other 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 elements. But it
traverse the elements. 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 [Link].*;
2. class TestArrayList21{
3. public static void main(String args[]){
4.
5. List<String> al=new ArrayList<String>();//creating arraylist
6. [Link]("Sonoo");//adding object in arraylist
7. [Link]("Michael");
8. [Link]("James");
9. [Link]("Andy");
10. //traversing elements using Iterator
11. Iterator itr=[Link]();
12. while([Link]()){
13. [Link]([Link]());
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 [Link].*;
2. class TestVector1{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();//creating vector
5. [Link]("umesh");//method of Collection
6. [Link]("irfan");//method of Vector
7. [Link]("kumar");
8. //traversing elements using Enumeration
9. Enumeration e=[Link]();
10. while([Link]()){
11. [Link]([Link]());
12. }
13. }
14. }
Test it Now

Output:

umesh
irfan
kumar

You might also like