0% found this document useful (0 votes)
11 views25 pages

Unit-4 Study Material Java

Java notes unit 4

Uploaded by

globalsam08
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
11 views25 pages

Unit-4 Study Material Java

Java notes unit 4

Uploaded by

globalsam08
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

Unit-4 Study Material

Java Collection Framework

1)Collection in Java--- The Collection in Java is a framework that provides an


architecture to store and manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such
as searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework


provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

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

2)Collection Framework in Java--- The Collection framework represents a


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

1. Interfaces and its implementations, i.e., classes


2. Algorithm
3. It provides readymade architecture.
4. It represents a set of classes and interfaces.
5. It is optional.

3) Hierarchy of Collection Framework ---

Let us see the hierarchy of Collection framework. The java.util package contains
all the classes and interfaces for the Collection framework.
4) Iterator Interface ---
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface

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

1 public boolean It returns true if the iterator has more elements otherwise it
hasNext() returns false.

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 less
used.
5) Collection Interface ---- The Collection interface is the interface which is
implemented by all the classes in the collection framework. It declares the
methods that every collection will have. In other words, we can say that the
Collection interface builds the foundation on which the collection framework
depends.

Some of the methods of Collection interface are Boolean add ( Object obj),
Boolean addAll ( Collection c), void clear(), etc. which are implemented by all
the subclasses of Collection interface.

6) List Interface --- List interface is the child interface of Collection interface. It
inhibits a list type data structure in which we can store the ordered collection of
objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and


Stack.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and
access the elements from the list.

7) ArrayList ---- The ArrayList class implements the List interface. It uses a
dynamic array to store the duplicate element of different data types. The
ArrayList class maintains the insertion order and is non-synchronized. The
elements stored in the ArrayList class can be randomly accessed. Consider the
following example.

1. import java.util.*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }

Output:

Ravi
Vijay
Ravi
Ajay

8) LinkedList ---- LinkedList implements the Collection interface. It uses a


doubly linked list internally to store the elements. It can store the duplicate
elements. It maintains the insertion order and is not synchronized. In LinkedList,
the manipulation is fast because no shifting is required.

Consider the following example.

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

Output:

Ravi
Vijay
Ravi
Ajay

9) Vector ---- Vector uses a dynamic array to store the data elements. It is similar
to ArrayList. However, It is synchronized and contains many methods that are
not the part of Collection framework.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. .add("Amit");
6. v.add("Ashish");
7. v.add("Garima");
8. Iterator<String> itr=v.iterator();
9. while(itr.hasNext()){
10. System.out.println(itr.next());
11. }
12. }
13. }

Output:
Ayush
Amit
Ashish
Garima

10) Stack ---- Stack

The stack is the subclass of Vector. It implements the last-in-first-out data


structure, i.e., Stack. The stack contains all of the methods of Vector class and
also provides its methods like boolean push(), boolean peek(), boolean
push(object o), which defines its properties.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Ayush
Garvit
Amit
Ashish
11) Queue Interface --- Queue Interface

Queue interface maintains the first-in-first-out order. It can be defined as an


ordered list that is used to hold the elements which are about to be processed.
There are various classes like PriorityQueue, Deque, and ArrayDeque which
implements the Queue interface.

Queue interface can be instantiated as:

1. Queue<String> q1 = new PriorityQueue();


2. Queue<String> q2 = new ArrayDeque();

There are various classes that implement the Queue interface, some of them are
given below.

PriorityQueue

The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow
null values to be stored in the queue.

Consider the following example.

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

Output:

head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj

ArrayDeque

ArrayDeque class implements the Deque interface. It facilitates us to use the


Deque. Unlike queue, we can add or delete the elements from both the ends.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection6{
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Gautam");
7. deque.add("Karan");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }

Output:

Gautam
Karan
Ajay

12) Set Interface--- Set Interface in Java is present in java.util package. It extends
the Collection interface. It represents the unordered set of elements which doesn't
allow us to store the duplicate items. We can store at most one null value in Set.
Set is implemented by HashSet, LinkedHashSet, and TreeSet.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();

13) HashSet --- HashSet class implements Set Interface. It represents the
collection that uses a hash table for storage. Hashing is used to store the elements
in the HashSet. It contains unique items.

Consider the following example.

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

Output:

Vijay
Ravi
Ajay

14) LinkedHashSet ---- LinkedHashSet class represents the LinkedList


implementation of Set Interface. It extends the HashSet class and implements Set
interface. Like HashSet, It also contains unique elements. It maintains the
insertion order and permits null elements.

Consider the following example.

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

Output:

Ravi
Vijay
Ajay

15) SortedSet Interface --- ortedSet is the alternate of Set interface that provides
a total ordering on its elements. The elements of the SortedSet are arranged in the
increasing (ascending) order. The SortedSet provides the additional methods that
inhibit the natural ordering of the elements.

The SortedSet can be instantiated as:

1. SortedSet<data-type> set = new TreeSet();

16) TreeSet--- Java TreeSet class implements the Set interface that uses a tree for
storage. Like HashSet, TreeSet also contains unique elements. However, the
access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored
in ascending order.

Consider the following example:

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

Output:

Ajay
Ravi
Vijay

17) Map Interface ---- A map contains values on the basis of key, i.e. key and
value pair. Each key and value pair is known as an entry. A Map contains unique
keys.A Map is useful if you have to search, update or delete elements on the basis
of a key.

1. import java.util.*;
2. public class MapExample1 {
3. public static void main(String[] args) {
4. Map map=new HashMap();
5. //Adding elements to map
6. map.put(1,"Amit");
7. map.put(5,"Rahul");
8. map.put(2,"Jai");
9. map.put(6,"Amit");
10. //Traversing Map
11. Set set=map.entrySet();//Converting to Set so that we can traverse
12. Iterator itr=set.iterator();
13. while(itr.hasNext()){
14. //Converting to Map.Entry so that we can get key and value separatel
y
15. Map.Entry entry=(Map.Entry)itr.next();
16. System.out.println(entry.getKey()+" "+entry.getValue());
17. }
18. }
19. }

Output

1.Amit
2. Jai
3. Rahul
4. Amit

18) HashMap Class---- Java HashMap class implements the Map interface
which allows us to store key and value pair, where keys should be unique. If you
try to insert the duplicate key, it will replace the element of the corresponding
key. It is easy to perform operations using the key index like updation, deletion,
etc. HashMap class is found in the java.util package.

HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It
allows us to store the null elements as well, but there should be only one null key.
Since Java 5, it is denoted as HashMap<K,V> where K stands for key and V for
value. It inherits the AbstractMap class and implements the Map interface.

HashMap class Parameters

Let's see the Parameters for java.util.HashMap class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.
o import java.util.*;
o public class HashMapExample1{
o public static void main(String args[]){
o HashMap<Integer,String> map=new HashMap<Integer,String>();//Cre
ating HashMap
o map.put(1,"Mango"); //Put elements in Map
o map.put(2,"Apple");
o map.put(3,"Banana");
o map.put(4,"Grapes");
o
o System.out.println("Iterating Hashmap...");
o for(Map.Entry m : map.entrySet()){
o System.out.println(m.getKey()+" "+m.getValue());
o }
o }
o }

19) LinkedHashMap Class---- Java LinkedHashMap class is Hashtable and


Linked list implementation of the Map interface, with predictable iteration
order. It inherits HashMap class and implements the Map interface.
LinkedHashMap class declaration

Let's see the declaration for java.util.LinkedHashMap class.


public class LinkedHashMap<K,V> extends HashMap<K,V> implements Ma
p<K,V>
1. import java.util.*;
2. class LinkedHashMap1{
3. public static void main(String args[]){
4.
5. LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,Str
ing>();
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. }

Output:100 Amit
101 Vijay
102 Rahul

20) TreeMap Class ---- Java TreeMap class is a red-black tree based
implementation. It provides an efficient means of storing key-value pairs in
sorted order.
o Java TreeMap contains values based on the key. It implements the
NavigableMap interface and extends AbstractMap class.
o Java TreeMap contains only unique elements.
o Java TreeMap cannot have a null key but can have multiple null values.
o Java TreeMap is non synchronized.
o Java TreeMap maintains ascending order.

TreeMap class declaration

Let's see the declaration for java.util.TreeMap class.


public class TreeMap<K,V> extends AbstractMap<K,V> implements Naviga
bleMap<K,V>, Cloneable, Serializable

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

Output:100 Amit
101 Vijay
102 Ravi
103 Rahul

What is difference between HashMap and TreeMap?

HashMap TreeMap

1) HashMap can contain one null key. TreeMap cannot contain any null key.

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

21) Hashtable Class ---- Java Hashtable class implements a hashtable, which
maps keys to values. It inherits Dictionary class and implements the Map
interface.
o A Hashtable is an array of a list. Each list is known as a bucket. The position
of the bucket is identified by calling the hashcode() method. A Hashtable
contains values based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is
0.75.

Hashtable class declaration

Let's see the declaration for java.util.Hashtable class.

public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,


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

Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
22) 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 a collection. If
collection elements are of a Set type, we can use TreeSet. However, we cannot sort the
elements of List. Collections class provides methods for sorting the elements of List
type elements.

Example to sort 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. }

Output

Mukesh
Saurav
Tahir
Viru
Example to sort string objects in reverse order
1. import java.util.*;
2. class TestSort2{
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,Collections.reverseOrder());
12. Iterator i=al.iterator();
13. while(i.hasNext())
14. {
15. System.out.println(i.next());
16. }
17. }
18. }
Viru
Tahir
Saurav
Mukesh

Example to sort Wrapper class objects


1. import java.util.*;
2. class TestSort3{
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. }
101
201
230

Example to sort user-defined class objects


1. import java.util.*;
2.
3. class Student implements Comparable<Student> {
4. public String name;
5. public Student(String name) {
6. this.name = name;
7. }
8. public int compareTo(Student person) {
9. return name.compareTo(person.name);
10.
11. }
12. }
13. public class TestSort4 {
14. public static void main(String[] args) {
15. ArrayList<Student> al=new ArrayList<Student>();
16. al.add(new Student("Viru"));
17. al.add(new Student("Saurav"));
18. al.add(new Student("Mukesh"));
19. al.add(new Student("Tahir"));
20.
21. Collections.sort(al);
22. for (Student s : al) {
23. System.out.println(s.name);
24. }
25. }
26. }
Mukesh
Saurav
Tahir
Viru

23) Comparable Interface ----

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

Let's see the example of the Comparable interface that sorts the list elements on
the basis of age.

File: Student.java

1. class Student implements Comparable<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.
11. public int compareTo(Student st){
12. if(age==st.age)
13. return 0;
14. else if(age>st.age)
15. return 1;
16. else
17. return -1;
18. }
19. }

File: TestSort1.java
1. import java.util.*;
2. public class TestSort1{
3. public static void main(String args[]){
4. ArrayList<Student> al=new ArrayList<Student>();
5. al.add(new Student(101,"Vijay",23));
6. al.add(new Student(106,"Ajay",27));
7. al.add(new Student(105,"Jai",21));
8.
9. Collections.sort(al);
10. for(Student st:al){
11. System.out.println(st.rollno+" "+st.name+" "+st.age);
12. }
13. }
14. }

105 Jai 21
101 Vijay 23
106 Ajay 27

24) Comparator Interface ---- Java Comparator interface

Java Comparator interface is used to order the objects of a 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 sequences, i.e., you can sort the elements on the basis
of any data member, for example, rollno, name, age or anything else.

Methods of Java Comparator Interface

Method Description

public int compare(Object obj1, It compares the first object with the second
Object obj2) object.
public boolean equals(Object obj) It is used to compare the current object with the
specified object.

public boolean equals(Object obj) It is used to compare the current object with the
specified object.

Java Comparator Example (Non-generic Old Style)

Let's see the example of sorting the elements of List 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

Student.java

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. 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 the age of the first object
is greater than the second, we are returning a positive value. It can be anyone such
as 1, 2, 10. If the age of the first object is less than the second object, we are
returning a negative value, it can be any negative value, and if the age of both
objects is 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. }

25) Properties Class in Java ---- The properties object contains key and value
pair both as a string. The java.util.Properties class 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 the properties file and store data into the
properties file. Moreover, it can be used to get the properties of a system.
An Advantage of the properties file

Recompilation is not required if the information is changed from a


properties file: If any information is changed from the properties file, you don't
need to recompile the java class. It is used to store information which is to be
changed frequently.

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

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. }

You might also like