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

Unit - V Java

Unit 5 of the Java Programming course covers adapter classes, inner classes, and the Java Util Package, focusing on the Collections Framework. It explains the purpose and advantages of using adapter classes for event handling, the role of inner classes in simplifying code, and the structure and benefits of the Collections Framework, including interfaces like Collection and List. Additionally, it discusses the Comparator interface for custom sorting of user-defined classes and introduces EnumSet for managing enumerated types.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Unit - V Java

Unit 5 of the Java Programming course covers adapter classes, inner classes, and the Java Util Package, focusing on the Collections Framework. It explains the purpose and advantages of using adapter classes for event handling, the role of inner classes in simplifying code, and the structure and benefits of the Collections Framework, including interfaces like Collection and List. Additionally, it discusses the Comparator interface for custom sorting of user-defined classes and introduces EnumSet for managing enumerated types.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Unit - V Java Programming III BCA

Unit – 5

Adapter classes - Inner classes -Java Util Package / Collections Framework:Collection &
Iterator Interface- Enumeration- List and ArrayList Vector- Comparator
Adapter Classes
Adapter Classes Java provides a special feature, called an adapter class, that can simplify the

creation of event handlers in certain situations. An adapter class provides an empty implementation

of all methods in an event listener interface. Adapter classes are useful when you want to receive

and process only some of the events that are handled by a particular event listener interface. You

can define a new class to act as an event listener by extending one of the adapter classes and

implementing only those events in which you are interested

For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and

mouseMoved( ), which are the methods defined by the MouseMotionListener interface. If you were

interested in only mouse drag events, then you could simply extend MouseMotionAdapter and

override mouseDragged( ).

As you can see by looking at the program, not having to implement all of the methods defined by

the MouseMotionListener and MouseListener interfaces saves you a considerable amount of effort

and prevents your code from becoming cluttered with empty methods. As an exercise, you might

want to try rewriting one of the keyboard input examples shown earlier so that it uses a KeyAdapter

1
Unit - V Java Programming III BCA

Inner Classes
An inner class is a class defined within another class, or even within an expression. This section
illustrates how inner classes can be used to simplify the code when using event adapter classes. To
understand the benefit provided by inner classes, consider the applet shown in the following listing.
It does not use an inner class.
s. Its goal is to display the string “Mouse Pressed” in the status bar of
the applet viewer or browser when the mouse is pressed. There are two :The The Java Library top-level
top
classes in this program. MousePressedDemo extends Applet, and MyMouseAdapter extends
MouseAdapter. The init( ) method of MousePressedDemo instantiates MyMouseAdapter and
provides this object as an argument to the addMouseListener( ) method.

2
Unit - V Java Programming III BCA

Java Util Package


The utility package, (java.util)) contains all the classes and interfaces that are required by the
collection framework. The collection framework contains an interface named an iterable interface
which provides the iterator to iterate through all the collections.
Collections in Java
Any group of individual objects that are represented as a single unit is known as a Java Collection
of Objects. In Java, a separate framework named the “Collection Framework” has been defined in
JDK 1.2 which holds all the Java Collection Classes and Interface in it.
In Java, the Collection interface ((java.util.Collection) and Map interface (java.util.Map
java.util.Map) are the
two main “root” interfaces of Java collection classes.
What is a Framework in Java?
A framework is a set of classes and interfaces which provide a ready-made
made architecture. In order to
implement a new feature or a class, there is no need to define a framework. However, an optimal
object-oriented
oriented design always includes a framework with a collection of classes such that all the
classes perform the same kind of task.
Need for a Separate Collection Framework in Java
Before the Collection Framework(or before JDK 1.2) was introduced, the standard methods for
grouping Java objects (or collections) were Arrays or Vectors, or Hashtables.
Hashtables All of these
collections
ns had no common interface. Therefore, though the main aim of all the collections is the
same, the implementation of all these collections was defined independently and had no correlation
among them. And also, it is very difficult for the users to remember all the different methods,
syntax, and constructors present in every collection class.
Let’s understand this with an example of adding an element in a hashtable and a vector.
3
Unit - V Java Programming III BCA
Collections are a cornerstone of Java programming. Whether you’re working with lists, sets, or
maps, a strong understanding of collections is crucial.
Advantages of the Java Collection Framework
Since the lack
ack of a collection framework gave rise to the above set of disadvantages, the following
are the advantages of the collection framework.
1. Consistent API: The API has a basic set of interfaces like Collection,
Collection Set, List, or Map, all
the classes (ArrayList, LinkedList, Vector, etc) that implement these interfaces
have some common set of methods.

2. Reduces programming effort: A programmer doesn’t have to worry about the design of the
Collection but rather he can focus on its best use in his program. Therefore, the basic
concept of Object-oriented
oriented programming (i.e.) abstraction has been successfully
implemented.

3. Increases program speed and quality: Increases performance by providing high- high
performance implementations of useful data structures and algorithms beca
because in this case,
the programmer need not think of the best implementation of a specific data structure. He
can simply use the best implementation to drastically boost the performance of his
algorithm/program.
Hierarchy of the Collection Framework in Java
The utility package, (java.util) contains all the classes and interfaces that are required by the
collection framework. The collection framework contains an interface named an iterable interface
which provides the iterator to iterate through all the collec
collections.
tions. This interface is extended by the
main collection interface which acts as a root for the collection framework. All the collections
extend this collection interface thereby extending the properties of the iterator and the methods of
this interface. The
he following figure illustrates the hierarchy of the collection framework.

4
Unit - V Java Programming III BCA
Before understanding the different components in the above framework, let’s first understand a
class and an interface.
 Class: A class is a user-defined
defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.

 Interface: Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, nobody). Interfaces
specify what a class must do and not how. It is the blueprint of the class.
Methods of the Collection Interface
This interface contains various methods which can be directly used by all the collections which
implement this interface. They are:

Interfaces that Extend the Java Collections Interface


The collection framework contains multiple interfaces where every interface is used to store a
specific type of data. The following are the interfaces present in the framework.

5
Unit - V Java Programming III BCA
1. Iterable Interface
This is the root interface for the entire collection framework. The collection interface extends the
iterable interface. Therefore, inherently, all the interfaces and classes implement this interface. The
main functionality of this interface is to provide an iterator for the collections. Therefore, this
interface contains only one abstract method which is the iterator. It returns the
Iterator iterator();
2. Collection Interface
This interface extends the iterable interface and is implemented by all the classes in the collection
framework. This interface contains all the basic methods which every collection has like adding the
data into the collection, removing the data, clearing the data, etc. All these methods are
implemented in this interface because these methods are implemented by all the classes irrespective
of their style of implementation. And also, having these methods in this interface ensures that the
names of the methods are universal for all the collections. Therefore, in short, we can say that this
interface builds a foundation on which the collection classes are implemented.
3. List Interface
This is a child interface of the collection interface. This interface is dedicated to the data of the list
type in which we can store all the ordered collections of the objects. This also allows duplicate data
to be present in it. This list interface is implemented by various classes like ArrayList, Vector, Stack,
etc. Since all the subclasses implement the list, we can instantiate a list object with any of these
classes.
For example:
List <T> al = new ArrayList<> ();
List <T>ll = new LinkedList<> ();
List <T> v = new Vector<> ();
Where T is the type of the object
The classes which implement the List interface are as follows:
i). ArrayList
ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard arrays
but can be helpful in programs where lots of manipulation in the array is needed. The size of an
ArrayList is increased automatically if the collection grows or shrinks if the objects are removed
from the collection. Java ArrayList allows us to randomly access the list. ArrayListcan not be used
for primitive types, like int, char, etc. We will need a wrapper class for such cases.
Let’s understand the ArrayList with the following example:
// Java program to demonstrate the
// working of ArrayList
import java.io.*;
import java.util.*;

6
Unit - V Java Programming III BCA
class GFG {

// Main Method
public static void main(String[] args)
{

// Declaring the ArrayList with


// initial size n
ArrayList<Integer> al = new ArrayList<Integer>();

// Appending new elements at


// the end of the list
for (int i = 1; i<= 5; i++)
al.add(i);

// Printing elements
System.out.println(al);

// Remove element at index 3


al.remove(3);

// Displaying the ArrayList


// after deletion
System.out.println(al);

// Printing elements one by one


for (int i = 0; i<al.size(); i++)
System.out.print(al.get(i) + " ");
}
}
Output

7
Unit - V Java Programming III BCA
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235
Vector
A vector provides us with dynamic arrays in Java. Though, it may be slower than standard arrays
but can be helpful in programs where lots of manipulation in the array is needed. This is identical to
ArrayList in terms of implementation. However, the primary difference between a vector and an
ArrayList is that a Vector is synchronized and an ArrayList is non-synchronized.
Let’s understand the Vector with an example:
// Java program to demonstrate the
// working of Vector
import java.io.*;
import java.util.*;

class GFG {

// Main Method
public static void main(String[] args)
{

// Declaring the Vector


Vector<Integer> v = new Vector<Integer>();

// Appending new elements at


// the end of the list
for (int i = 1; i<= 5; i++)
v.add(i);

// Printing elements
System.out.println(v);

// Remove element at index 3


v.remove(3);
8
Unit - V Java Programming III BCA

// Displaying the Vector


// after deletion
System.out.println(v);

// Printing elements one by one


for (int i = 0; i<v.size(); i++)
System.out.print(v.get(i) + " ");
}
}

Enumerations or popularly known as enum serve the purpose of representing a group of named
constants in a programming language. For example, the 4 suits in a deck of playing cards may be 4
enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named
Suit.
The EnumSet is one of the specialized implementations of the Set interface for use with
the enumeration type. A few important features of EnumSet are as follows:
 It extends AbstractSet class and implements Set Interface in Java.
 EnumSet class is a member of the Java Collections Framework & is not synchronized.
 It’s a high-performance set implementation, much faster than HashSet.
 All of the elements in an EnumSet must come from a single enumeration type that is
specified when the set is created either explicitly or implicitly.
 It does not allow null Objects and throws NullPointerException if we do so.
 It uses a fail-safe iterator, so it won’t throw ConcurrentModificationException if the
collection is modified while iterating.
 The Hierarchy of EnumSet is as follows:
 java.lang.Object
↳java.util.AbstractCollection<E>
↳java.util.AbstractSet<E>
↳java.util.EnumSet<E>

9
Unit - V Java Programming III BCA

Syntax: Declaration
public abstract class EnumSet<E extends Enum<E>>
Here, E specifies the elements. E must extend Enum, which enforces the requirement that the
elements must be of the specified enum type.
Benefits of using EnumSet
 Due to its implementation using RegularEnumSet and JumboEnumSet, all the methods in
an EnumSet are implemented using bitwise arithmetic operations.
 EnumSet is faster
ster than HashSet because we no need to compute any hashCode to find the
right bucket.
 The computations are executed in constant time and the space required is very little.
// Java Program to Illustrate Working
// of EnumSet and its functions

// Importing required classes


import java.util.EnumSet;

// Enum
enumGfg{ CODE, LEARN, CONTRIBUTE, QUIZ, MCQ };

// Main class
// EnumSetExample
public class GFG {

10
Unit - V Java Programming III BCA
// Main driver method
public static void main(String[] args) {

// Creating a set
EnumSet<Gfg> set1, set2, set3, set4;

// Adding elements
set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE,
Gfg.LEARN, Gfg.CODE);
set2 = EnumSet.complementOf(set1);
set3 = EnumSet.allOf(Gfg.class);
set4 = EnumSet.range(Gfg.CODE, Gfg.CONTRIBUTE);

// Printing corresponding elements in Sets


System.out.println("Set 1: " + set1);
System.out.println("Set 2: " + set2);
System.out.println("Set 3: " + set3);
System.out.println("Set 4: " + set4);
}
}

The EnumSet Class EnumSet extends AbstractSet and implements Set. It is specifically for use with
keys of an enum type. It is a generic class that has this declaration: class EnumSet> Here, E
specifies the elements. Notice that E must extend Enum, which enforces the requirement that the
elements must be of the specified enum type. EnumSet defines no constructors. Instead, it uses the
factory methods shown in Table 17-7 to create objects. All methods can throw
NullPointerException. The copyOf( ) and range( ) methods can also throw
IllegalArgumentException. Notice that the of( ) method is overloaded a number of times. This is in
the interest of efficiency. Passing a known number of arguments can be faster than using a vararg
parameter when the number of arguments is small.
Java Comparator Interface

The Comparator interface is essential for custom sorting in Java. Understanding its proper
implementation can help you write cleaner and more efficient code Java Comparator interface
Java Comparator interface is used to order the objects of a user-defined class.

11
Unit - V Java Programming III BCA
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


It compares the first object with the second object.
obj1, Object obj2)

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

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

A comparator interface is used to order the objects of user-defined classes. A comparator object is
capable of comparing two objects of the same class. Following function compare obj1 with obj2.
Syntax:
public int compare(Object obj1, Object obj2):
Suppose we have an Array/ArrayList of our own class type, containing fields like roll no, name,
address, DOB, etc, and we need to sort the array based on Roll no or name?

The Comparator interface is essential for custom sorting in Java. Understanding its proper
implementation can help you write cleaner and more efficient code.
Method 1: One obvious approach is to write our own sort() function using one of the standard
algorithms. This solution requires rewriting the whole sorting code for different criteria like Roll
No. and Name.
Method 2: Using comparator interface- Comparator interface is used to order the objects of a
user-defined class. This interface is present in java.util package and contains 2 methods
compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort
the elements based on data members. For instance, it may be on roll no, name, age, or anything
else.

Method of Collections class for sorting List elements is used to sort the elements of List by the
given comparator. .

public void sort(List list, ComparatorClass c)


To sort a given List, ComparatorClass must implement a Comparator interface.
How do the sort() method of Collections class work?
12
Unit - V Java Programming III BCA
Internally the Sort method does call Compare method of the classes it is sorting. To compare two
elements, it asks “Which is greater?” Compare method returns -1, 0, or 1 to say if it is less than,
equal, or greater to the other. It uses this result to then determine if they should be swapped for
their sort.

// Java Program to Demonstrate Working of

// Comparator Interface

// Importing required classes

import java.io.*;
import java.lang.*;
import java.util.*;

// Class 1
// A class to represent a Student
class Student {

// Attributes of a student
int rollno;
String name, address;

// Constructor
public Student(int rollno, String name, String address)
{

// This keyword refers to current instance itself


this.rollno = rollno;
this.name = name;
this.address = address;
}

// Method of Student class


// To print student details in main()
public String toString()
{

// Returning attributes of Student


return this.rollno + " " + this.name + " "
+ this.address;
}
}

// Class 2
// Helper class implementing Comparator interface
class Sortbyroll implements Comparator<Student> {

// Method
// Sorting in ascending order of roll number
public int compare(Student a, Student b)
{
13
Unit - V Java Programming III BCA

return a.rollno - b.rollno;


}
}

// Class 3
// Helper class implementing Comparator interface
class Sortbyname implements Comparator<Student> {

// Method
// Sorting in ascending order of name
public int compare(Student a, Student b)
{

return a.name.compareTo(b.name);
}
}

// Class 4
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an empty ArrayList of Student type


ArrayList<Student> ar = new ArrayList<Student>();

// Adding entries in above List


// using add() method
ar.add(new Student(111, "Mayank", "london"));
ar.add(new Student(131, "Anshul", "nyc"));
ar.add(new Student(121, "Solanki", "jaipur"));
ar.add(new Student(101, "Aggarwal", "Hongkong"));

// Display message on console for better readability


System.out.println("Unsorted");

// Iterating over entries to print them


for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));

// Sorting student entries by roll number


Collections.sort(ar, new Sortbyroll());

// Display message on console for better readability


System.out.println("\nSorted by rollno");

// Again iterating over entries to print them


for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
14
Unit - V Java Programming III BCA

// Sorting student entries by name


Collections.sort(ar, new Sortbyname());

// Display message on console for better readability


System.out.println("\nSorted by name");

// // Again iterating over entries to print them


for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
}
}

(Unit – V Completed)

15

You might also like