UNIT V
ADAPTER CLASS and INNER CLASS
Java Adapter class provide the default implementation of listener interfaces. If you inherit the
adapter class, you will need not be forced to provide the implementation of all the methods of listener
interfaces. The adapter classes with their corresponding listener interfaces are given below.
[Link]. Adapter Class
For example, MouseAdapter provides empty implementations for all MouseListener methods, allowing you
to override only the mouseClicked method if that's the only event you're interested in.
import [Link];
import [Link];
import [Link];
import [Link];
public class AdapterExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Adapter Example");
JPanel panel = new JPanel();
[Link](new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked at: " + [Link]() + ", " + [Link]());
}
});
[Link](panel);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}}
INNER CLASS (nested class)
It is a class that is declared inside a class or interface. We use this to logically group classes and interfaces in
one place to be more readable and maintainable. Sometimes users need to program a class in such a way so
that no class can access it.
Syntax:
class java_outerclass{
//code
class java_innerclass
{
//code}}
PROGRAMMING IN JAVA , ATASC -THIRUKAZHUKUNDRAM
EXAMPLE
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class InnerClassExample {
private JFrame frame;
private JLabel label;
private JButton button;
public InnerClassExample() {
frame = new JFrame("Inner Class Example");
[Link](new FlowLayout());
label = new JLabel("Button not clicked yet");
button = new JButton("Click me");
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked!");
}
});
[Link](label);
[Link](button);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
public static void main(String[] args) {
new InnerClassExample();
}
}
In this example, the ActionListener is implemented as an anonymous inner class, giving it direct access to
the label instance variable of the InnerClassExample class.
[Link] PACKAGE / COLLECTIONS FRAMEWORK
The Java Collections Framework provides a set of interfaces, classes, and algorithms for working
with groups of objects (collections). It includes different types of collections such as lists, sets, and maps,
and defines a common set of methods for working with them. It provides a way to manage and manipulate
data in a consistent manner.
Hierarchy of the Collection Framework
The utility package, ([Link]) 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.
PROGRAMMING IN JAVA , ATASC -THIRUKAZHUKUNDRAM
Collection Interface
The Collection interface is the root interface in the Java Collections Framework. It defines basic operations
such as adding, removing, and querying the elements of a collection. It has two main subinterfaces:
List: A collection that maintains the order of elements, allowing duplicates. Elements can be
accessed via an index.
Set: A collection that doesn't allow duplicate elements. It does not guarantee the order of elements.
Queue: A collection used for holding elements prior to processing. Elements are generally added to
the end and removed from the front.
Deque: A double-ended queue that allows elements to be added or removed from both ends.
Methods of Collection Interface:
add() - inserts the specified element to the collection
size() - returns the size of the collection
remove() - removes the specified element from the collection
iterator() - returns an iterator to access elements of the collection
addAll() - adds all the elements of a specified collection to the collection
removeAll() - removes all the elements of the specified collection from the collection
clear() - removes all the elements of the collection
Example
import [Link].*;
public class CollectionExample {
public static void main(String[] args) {
PROGRAMMING IN JAVA , ATASC -THIRUKAZHUKUNDRAM
// Create a Collection of Strings using HashSet (which implements Collection)
Collection<String> collection = new HashSet<>();
// Add elements to the collection
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Date");
// Display the collection
[Link]("Collection: " + collection);
// Check if a particular element is in the collection
[Link]("Contains 'Banana': " + [Link]("Banana")); // true
[Link]("Contains 'Mango': " + [Link]("Mango")); // false
// Get the size of the collection
[Link]("Size of collection: " + [Link]()); // 4
// Remove an element from the collection
[Link]("Apple");
[Link]("Collection after removing 'Apple': " + collection);
// Check if the collection is empty
[Link]("Is the collection empty? " + [Link]()); // false
// Clear the collection
[Link]();
[Link]("Collection after clearing: " + collection);
[Link]("Is the collection empty now? " + [Link]()); // true
}
}
Iterator Interface
The Iterator interface provides methods for iterating over collections in Java. It is the most commonly used
way to traverse through the elements of a collection. Iterator is a more modern interface compared to the
older Enumeration interface.
Methods of Iterator Interface:
hasNext(): Returns true if there are more elements to iterate over.
next(): Returns the next element in the iteration.
remove(): Removes the last element returned by the iterator.
Example
import [Link].*;
public class IteratorExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
Iterator<String> iterator = [Link]();
while ([Link]()) {
[Link]([Link]());
}
}
}
OUTPUT
Apple
Banana
Cherry
The Iterator interface is preferred for traversing collections because it provides a more flexible, fail-
fast mechanism when iterating over a collection. This prevents Concurrent Modification Exceptions.
PROGRAMMING IN JAVA , ATASC -THIRUKAZHUKUNDRAM
Enumeration Interface
Before the Iterator interface was introduced, Java used the Enumeration interface for iterating over
collections. The Enumeration interface is considered legacy but is still present in older APIs, such as those
in the Vector and Stack classes.
Methods of Enumeration Interface:
hasMoreElements(): Returns true if there are more elements in the collection.
nextElement(): Returns the next element.
Example:
import [Link].*;
public class EnumerationExample {
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
[Link]("Java");
[Link]("Python");
[Link]("C++");
Enumeration<String> enumeration = [Link]();
while ([Link]()) {
[Link]([Link]());
}
}
}
Output:
Java
Python
C++
While Iterator is preferred over Enumeration, it still plays an important role in maintaining backward
compatibility.
List and ArrayList
List Interface: A List is an ordered collection (also known as a sequence). It allows duplicate
elements and maintains the insertion order. Elements in a List can be accessed by their index.
ArrayList: An implementation of the List interface backed by a dynamic array. It provides fast
random access to elements but may be slower when inserting or deleting elements in the middle of
the list due to the shifting of elements.
Methods of List Interface:
add(E e): Adds an element at the end of the list.
add(int index, E element): Adds an element at the specified index.
get(int index): Retrieves the element at the specified index.
set(int index, E element): Replaces the element at the specified index.
remove(int index): Removes the element at the specified index.
Example:
import [Link].*;
public class ArrayListExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Element at index 1: " + [Link](1)); // Output: Banana
[Link](0); // Removes "Apple"
[Link]("List after removal: " + list); // Output: [Banana, Cherry]
}
}
PROGRAMMING IN JAVA , ATASC -THIRUKAZHUKUNDRAM
Vector
Vector is a dynamic array-like structure, much like ArrayList, but it is synchronized. This means
that it is thread-safe but can be slower due to synchronization overhead. As a result, it is not
commonly used in modern applications, and ArrayList is usually preferred.
Methods of Vector:
add(E e): Adds an element to the vector.
elementAt(int index): Retrieves an element at the specified index.
removeElement(Object obj): Removes the first occurrence of the specified element.
ensureCapacity(int minCapacity): Ensures that the vector has enough capacity to accommodate new
elements.
Example:
import [Link].*; [Link]("Element at index 2: " +
public class VectorExample { [Link](2)); // Output: Python
public static void main(String[] args) { [Link]("C#"); // Removes
Vector<String> vector = new Vector<>(); "C#"
[Link]("Java"); [Link]("Vector after removal: " +
[Link]("C#"); vector); // Output: [Java, Python]
[Link]("Python"); }
}
Vector is mostly used in legacy systems, and its usage is generally discouraged in favor of more modern
alternatives like ArrayList.
6. Comparator Interface
The Comparator interface is used to define custom ordering of objects. While the Comparable interface
allows objects to compare themselves, Comparator is used when the sorting logic needs to be external or
when multiple sorting orders are required.
Methods of Comparator Interface:
int compare(T o1, T o2): Compares two objects o1 and o2. It returns:
o A negative value if o1 is less than o2.
o Zero if they are equal.
o A positive value if o1 is greater than o2.
boolean equals(Object obj): Compares the comparator with another object.
Example:
import [Link].*; }
class Employee {
String name; public class ComparatorExample {
int age; public static void main(String[] args) {
public Employee(String name, int age) { List<Employee> employees = new
[Link] = name; ArrayList<>();
[Link] = age; [Link](new Employee("Alice", 30));
} [Link](new Employee("Bob", 25));
public String toString() { [Link](new Employee("Charlie",
return name + ": " + age; 28));
}
} [Link](employees, new
class AgeComparator implements AgeComparator());
Comparator<Employee> { [Link]("Sorted employees by
public int compare(Employee e1, Employee e2) age: " + employees);
{ }
return [Link] - [Link]; // Sorting by age }
}
Output:
Sorted employees by age: [Bob: 25, Charlie: 28, Alice: 30]
The Comparator interface is useful for sorting complex objects or when there are multiple sorting criteria. It
is also helpful in GUI applications like Java Swing to sort data displayed in components like tables.
END OF UNIT V
PROGRAMMING IN JAVA , ATASC -THIRUKAZHUKUNDRAM