Java Collections Framework Overview
Java Collections Framework Overview
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).
Collection framework represents a unified architecture for storing and manipulating group of objects. It has:
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 ?
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.
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
There are only three methods in the Iterator interface. They are:
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.
For more information of java generics, click here Java Generics Tutorial.
In the above example, we have seen traversing ArrayList by Iterator. Let's see the example to traverse
ArrayList elements using for-each loop.
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.
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]
Output:Ajay
Vijay
Ravi
Output:>Ravi
Vijay
Ajay
Output:Ajay
Ravi
Vijay
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
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.
Output:102 Rahul
100 Amit
101 Vijay
HashSet contains only values whereas HashMap contains entry(key and value).
Output:100 Amit
101 Vijay
103 Rahul
Output:100 Amit
101 Vijay
102 Ravi
103 Rahul
1) HashMap is can contain one null key. TreeMap can not contain any null key.
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
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.
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.
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.
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 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.
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.
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.
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.
public void sort(List list,Comparator c): is used to sort the elements of List by the given comparator.
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
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.
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.
Method Description
public void load(InputStream is) loads data from the InputStream object
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.
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.
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
...........
[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. }
[Link]
1. #Javatpoint Properties Example
2. #Thu Oct 03 22:35:53 IST 2013
3. email=sonoojaiswal@[Link]
4. name=Sonoo Jaiswal
But there are many differences between ArrayList and Vector classes that are given below.
ArrayList Vector
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.
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.
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
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