5th Module Java
5th Module Java
• Collection
• Collection Interface –List, Set, Map, Collection Classes- Array List, HashSet
• HashMap
• Using an Iterator- For-Each-Comparators
• Wrapper classes
• Motivation for Generic Programming
• Generic Classes and Methods
• Bounded Types
• Wildcard Arguments
• Generic Constructors and Interfaces
2
Collections
3
Collections
• A Collection represents a single unit of objects, i.e., a group.
• The Collection is a framework that provides an architecture to store
and manipulate the group of objects.
• Java Collections can achieve all the operations performing on a data
such as searching, sorting, insertion, manipulation, and deletion.
4
Collections
Framework:
5
Collection Framework Hierarchy
Extends: Extends is a
keyword that is used for
developing inheritance
between two classes and
two interfaces.
Implements: Implements
is a keyword used for
developing inheritance
between class and
interface.
6
Collection Interface
• Interface contains methods and variables, but the methods only declared in an interface
(only method signature, no method definition).
• Collection interface extends the iterable interface and is implemented by all the classes
in the collection framework.
• This interface contains all the basic methods such as adding the data into the collection,
removing the data, clearing the data, etc.
a) add(Object) – This method is used to add an object to the collection.
b) addAll(Collection c) – It adds all the elements in the given collection to this collection.
c) clear() – This method removes all the elements from this collection.
d) remove(Object o) – It removes the given object from the collection. If duplicate values
exist, then removes the first occurrence of the object
• All these methods are implemented by all the classes. Existence of these methods in this
interface ensures the methods are universal for all the collections i.e., collection interface
builds a foundation on which the collection classes are implemented. 7
List Interface
• List Interface is a child interface of the collection interface.
• It is dedicated to the data of the list type in which user can store all the ordered collection of
the objects. This also allows duplicate data.
• The classes implements the List Interface are ArrayList, Vector, Stack, LinkedList, etc.
• Since all the subclasses implement the list, user can instantiate a list object with any of these
classes.
Syntax:
• ArrayList < data_type > x = new ArrayList < data_type > ();
• LinkedList < data_type > y = new LinkedList < data_type > ();
• Vector < data_type > z = new Vector < data_type > ();
• Stack < data_type > z = new Stack < data_type > ();
Create an ArrayList
8
ArrayList Class
• It implements a dynamic array by extending AbstractList.
9
ArrayList Example
import [Link].*;
import [Link].*;
class Main
{
public static void main (String[]args)
{
// Declaring the ArrayList
ArrayList < Integer > al = new ArrayList < Integer > ();
// Appending new elements
for (int i = 100; i <= 105; i++)
[Link] (i);
[Link] (al);
// Remove element at index 3
[Link] (3);
[Link] (al);
for (int i = 0; i < [Link] (); i++)
[Link] ([Link] (i) + " ");
}
} 10
Linked List Class
• LinkedList implements the Collection interface.
• It is a linear data structure where the elements are not stored in contiguous locations and
every element is a separate object with a data part and address part.
• The elements are linked using pointers and addresses. Each element is known as a node.
• It maintains the insertion order and is not synchronized. In LinkedList, the manipulation is
fast because no shifting is required.
11
Linked List Example 1
import [Link].*;
public class Main
{
public static void main (String args[])
{
LinkedList < String > al = new LinkedList < String > ();
[Link] ("Sai");
[Link] ("Srinivas");
[Link] ("Pavan");
[Link] ("Pavani");
Iterator < String > itr = [Link] ();
while ([Link] ())
{
[Link] ([Link] ());
}
}
}
12
Linked List Example 2
import [Link].*;
import [Link].*;
class Main
{
public static void main (String[]args)
{
LinkedList < Integer > x = new LinkedList < Integer > ();
for (int i = 1; i <= 5; i++)
[Link] (i);
[Link] (x);
[Link] (3);
[Link] (x);
}
}
13
Vector Class
• Vector uses a dynamic array to store the data elements.
import [Link].*;
public class Main
{
public static void main (String args[])
{
Vector < String > v = new Vector < String > ();
[Link] ("Sai");
[Link] ("Srinivas");
[Link] ("Pavan");
Iterator < String > itr = [Link]();
while ([Link]())
{
[Link] ([Link]()); 14
}}}
Vector Class
import [Link].*;
import [Link].*;
class Main
{
public static void main (String[]args)
{
Vector < Integer > v = new Vector < Integer > ();
for (int i = 101; i <= 105; i++)
[Link] (i);
[Link] (v);
[Link] (3);
[Link] (v);
}
}
15
Stack Class
• The stack is the subclass of Vector.
• In addition to the push and pop operations, the class provides three more functions
of empty, search and peek
16
Stack Class
import [Link].*;
public class Main
{
public static void main (String args[]) {
Stack < String > stack = new Stack < String > ();
[Link] ("Sai");
[Link] ("Sree");
[Link] ("Felix");
Iterator < String > itr = [Link]();
while ([Link]())
{
[Link] ([Link]());
}
[Link] ();
itr = [Link]();
[Link] ("After Popping");
while ([Link]())
{
[Link] ([Link]());
}}} 17
Set Interface
• Set Interface extends the Collection interface.
18
HashSet Class
• HashSet class implements Set Interface.
• It represents the collection that uses a hash table as a storage.
• Hashing is used to store the unique elements in the HashSet.
import [Link].*;
public class Main
{
public static void main (String args[]) {
//CreatingHashSet
HashSet < String > set = new HashSet < String > ();
[Link] ("Jai");
[Link] ("Vineet");
[Link] ("Raj");
[Link] ("Raj"); //Duplicate
//Traversingelements
Iterator < String > itr = [Link] ();
while ([Link] ())
{
[Link] ([Link] ());
}}} 19
Map Interface
• A map is a data structure that supports the key-value pair mapping for the data.
• Map doesn’t support duplicate keys because the same key cannot have multiple
mappings.
• A map is useful if there is a data, user can perform operations based on the key.
• Instantiate a map object with any of these classes due to all the subclasses
implement the map
20
HashMap Class
• Map interface is frequently implemented by HashMap.
• It stores the data in (Key, Value) pairs.
• To access a value in a HashMap, user must know its key.
• HashMap uses a technique called Hashing which converts a large String to small String that
represents the same String.
• So, the indexing and search operations are faster. HashSet also uses HashMap internally
[Link] Interface:
• Entry is the sub interface of Map. It can be accessed it by [Link] name.
• It returns a collection-view of the map, whose elements belong to this class.
• It provides methods to get key and value.
21
HashMap Class - Example
import [Link].*;
public class Main
{
public static void main (String args[])
{
HashMap < Integer, String > h = new HashMap < Integer, String > ();
[Link] (1, "Hi");
[Link] (2, "Welcome");
[Link] (3, "To VIT-AP");
// Finding the value for a key
[Link] ("Value for 1 is " + [Link] (1));
// Traversing
for ([Link] < Integer, String > e:[Link] ())
[Link] ([Link] () + " " + [Link] ());
}
}
22
Iterator Interface
• Iterator interface retrieves elements one by one from collection.
• next() - It returns the current element and moves the cursor pointer to the next element.
23
Iterator Example
import [Link].*;
import [Link].*;
class Main
{
public static void main (String[]args) {
ArrayList < String > al = new ArrayList < String > ();
[Link] ("Sai");
[Link] ("Srinivas");
[Link] ("Pavan");
Iterator < String > itr = [Link] ();
while ([Link] ()) {
[Link] ([Link] ());
// deletes last element
}
Iterator < String > i = [Link] ();
String str = "";
while ([Link] ()) {
str = (String) [Link] ();
if ([Link] ("Sai")) {
[Link] ();
[Link] ("\nThe element is removed");
break; } }
while ([Link] ()) {
[Link] ([Link] ());
} }
}
24
Iterator Interface
• The Iterable interface is the root interface for all the collection classes.
• To use for loop to elements, the class must implement the iterable interface.
• for-each loop uses iterable interface internally for iterating over objects of the implemented class.
• Iterables does not have a current state, rather it delivers an iterator method.
• It contains only one abstract method is the iterator() that internally called by iterable interface.
Steps to implement:
• Implement an iterable interface using the class whose object needs access to for-each loop.
• Any class that implements the iterable interface should Override the iterator() method provide by iterable
interface.
• The iterable does not maintain a current state so return an instance of iterator() method
25
import [Link]; // Method to check if there is a next element
import [Link]; @Override
public boolean hasNext() {
// Generic class Simple implementing Iterable interface return cursor < [Link]();
class Simple<T> implements Iterable<T> { }
private T[] elements; // Array to hold the elements
private int size; // Size of the array // Method to get the next element
@Override
// Constructor to initialize the elements and size public T next() {
public Simple(T[] elements) { if (!hasNext()) {
[Link] = elements; throw new NoSuchElementException();
[Link] = [Link]; } }
return [Link]()[cursor++];
// Overriding the iterator method to return an instance of CustomIterator }
@Override
public Iterator<T> iterator() { // Method to remove an element (not implemented)
return new CustomIterator<>(this); } @Override
public void remove() {
// Getter for the elements array throw new UnsupportedOperationException();
public T[] getElements() { }
return elements; } }
}
// Getter for the size class Main {
public int getSize() { public static void main(String[] args) {
return size; } Integer[] numbers = {1, 2, 3, 4, 5}; // Create an array
// CustomIterator class implementing Iterator interface of integers
private class CustomIterator<T> implements Iterator<T> { Simple<Integer> simple = new Simple<>(numbers); //
private int cursor; // Pointer to track the current position Create a Simple object with the array
private Simple<T> simple; // Reference to the Simple object
// Iterate over the Simple object using the for-each loop
// Constructor to initialize the Simple reference and cursor for (Integer num : simple) {
public CustomIterator(Simple<T> simple) { [Link](num); // Print each element
[Link] = simple; }
[Link] = 0; // Initialize cursor to the start } }
} 26
Comparator Interface
• A comparator interface is used to order (ascending) the objects of user-defined classes.
• A comparator object is capable of comparing two objects of two different classes.
29
Wrapper class in Java
• The wrapping is the mechanism of converting primitive (int, char, float, etc) into object and object into
primitive.
• Java is an OOP language that deals with objects mostly in Collections, Serialization, Synchronization, etc.
• Ex: Using primitive data type
int i = 10;
• The object representation Using wrapper class:
Integer ref = new Integer(i);
• For all the primitive data types, there are corresponding wrapper classes.
• Storing primitive types in the form of objects affects the performance in terms of memory
and speed
Example:
• Representing an integer via a wrapper takes about 12-16 bytes, compared to 4 in an
actual integer.
31
Wrapper class Hierarchy in Java
32
Primitive data type and Corresponding Wrapper classes
35
Integer Wrapper class
public static String toBinaryString(int i)
• find base 2(with no extra leading 0s (zeros)) for the given int.
public static String toOctalString(int i)
• find base 8 (with no extra leading 0s (zeros)) for the given int.
public static String toHexString(int i)
• find base 16(with no extra leading 0s (zeros)) for the given int.
37
Character Wrapper class
• Character class is a wrapper class for character data types
• After a Character object is created, user can retrieve the primitive character value
from it using:
char charValue( )
38
public class Main {
public static void main (String ar[]) {
String input = "Hi, Sachin Is My Favorite Cricketer!";
char[] a = [Link] ();
int alpha = 0, upper = 0, lower = 0, symbol = 0, digit = 0, space = 0;
for (char c:a)
{
if ([Link] (c))
Character alpha++;
if ([Link] (c))
Wrapper class digit++;
if ([Link] (c))
- Example upper++;
if ([Link] (c))
lower++;
if ([Link] (c))
space++;
}
symbol = [Link] - (alpha + digit + space);
[Link] ("[Link] alphabets " + alpha);
[Link] ("[Link] digits " + digit);
[Link] ("[Link] upper case " + upper);
[Link] ("[Link] lower case " + lower);
[Link] ("[Link] spaces " + space);
[Link] ("[Link] symbols " + symbol);
}
}
39
Boolean Wrapper class
• The Boolean class is a wrapper class for boolean values
Boolean(String str)
• The object created by constructor have the value true or false
depending upon the string value in str is “true” or “false”.
40
Convert primitive datatype to Wrapper (Autoboxing)
class Main {
public static void main (String[]args) {
// create primitive types
int a = 10;
double b = 100.12;
Integer Obj1 = [Link] (a); //converts into wrapper objects
Double Obj2 = [Link] (b);
if (Obj1 instanceof Integer)
{
[Link] ("An object of Integer is created.");
}
if (Obj2 instanceof Double)
{
[Link] ("An object of Double is created.");
}
}
}
41
Convert wrapper to primitive (Unboxing)
public class Main
{
public static void main (String args[])
{
//Converting Integer to int
Integer a = new Integer (3);
int i = [Link] (); //converts Integer to int explicitly
int j = a; //unboxing, now compiler writes [Link]() internally
[Link] (a + " " + i + " " + j);
}
}
42
Generic Programming
43
Generics
• A class, interface, or method that operates on a parameterized type is called generic.
• Generics is used to create a single class, interface, and method that can be used with
different types of data (objects).
• Generics means parameterized types.
Advantage of Generics:
44
Advantages of Generics
Type casting is not required: There is no need to typecast the object
//Without generics //With Generics, need not to typecast the object.
List al = new ArrayList(); List<String> al = new ArrayList<String>();
[Link]("hello"); [Link]("hello");
String s = (String) [Link](0); //typecasting String s = [Link](0);
• Compile-Time Checking: It checks at compile time. So, Issues will not raise at run-
time. It is better to handle the problem at compile time than runtime.
45
Generic Programming: Type parameters
T - Type
E - Element
K - Key
N - Number
V - Value
46
General Form of a Generic Class
❖Class refers any type is a generic class. T type parameter is used to
create the generic class of specific type.
❖Syntax to Create a generic class:
class class_name<T>{
T obj;
void set(T obj){ ▪ T type indicates any type
[Link]=obj; such as String, Integer, and
} Float.
T get(){ ▪ The type is used to store
return obj; and retrieve the data.
}
} 47
Create object for Generic Class
❖Syntax to Create Object using generic class:
class-name<type-arg-list > var-name = new class-name<type-arg-list>(arg-list);
❖ Example:
Set<Integer> set=new HashSet<Integer>(50);
import [Link].*;
public class Main {
public static void main (String[]args) {
Set < Integer > set = new HashSet < Integer > ();
[Link] (23);
[Link] (12);
Iterator < Integer > it = [Link] ();
int sum = 0;
while ([Link] ())
sum += [Link] ();
[Link] (sum);
}
} 48
Generic Class Example
class Mark < T > { public class Main {
T obj; public static void main (String[]arg) {
Mark (T obj) { Mark < Integer > sem1 = new Mark < Integer > (81);
[Link] = obj; [Link] ("class Mark is of type:" + sem1);
} [Link] ([Link] ());
public T getObj () { Mark < Float > sem2 = new Mark < Float > (15.25f);
return obj; [Link] ("class Mark is of type:" + sem2);
} [Link] ([Link] ());
public void setObj (T obj) { }}
[Link] = obj;
}
public String toString () {
return [Link] ().getName ();
}
}
49
Ex1: Generic Class with Two Type Parameters
import [Link];
import [Link];
public class Main {
public static void main (String[]args) {
Map < Character, Integer > count = new HashMap < Character, Integer > ();
String inp = "OOP in SCOPE";
// Iterating through each character in the input string
for (char c:[Link] ()) {
// If the character is already in the map, increment its count
if ([Link] (c)) {
[Link] (c, [Link] (c) + 1);}
else {
// Otherwise, add the character to the map with a count of 1
[Link] (c, 1);}
}
// Iterating through the entries of the map to print the character counts
for ([Link] entry:[Link] ()) {
[Link] ([Link] () + " occurs " + [Link] ());}
}
}
50
Ex 2: Generic Class with Two Type Parameters
class Student < T, U > {
T rno; public class Main {
U rank; public static void main (String[]arg) {
public Student (T rno, U rank) { Student < String, Integer > s1 = new Student < String, Integer >
[Link] = rno; ("23BCE7010", 2);
[Link] = rank; [Link] (s1);
} Student < Integer, String > s2 = new Student < Integer, String >
public T getRno () { (10005, "10");
return rno; [Link] (s2);
} }}
public void setRno (T rno) {
[Link] = rno;
}
public U getRank () {
return rank;
}
public void setRank (U rank) {
[Link] = rank;
}
public String toString () {
return "Student [rno=" + rno + ", rank=" + rank + "]";
}
}
51
Generic method
• Generic method allows any type of parameters.
• The scope of parameters is only inside the method.
• It allows static and non-static methods
❖Example
< E > void ShowArray(E[] elements)
52
Generic method: Example
public class Main {
public static <E > void ShowArray (E[]elements)
{
for (E s:elements) {
[Link] (s + " ");
}
[Link] ();
}
public static void main (String args[]) {
Integer[]intArray = { 1, 2, 5, 70, 9 };
Character[]chArray = { 'V', 'I', 'T', '-', 'A', 'P' };
[Link] ("Integer Array");
ShowArray (intArray);
[Link] ("Character Array");
ShowArray (chArray);
}
}
53
Generic Interface
❑ Generic interface allows any type of parameters.
class Main {
public static void main (String args[]) {
GenCons test = new GenCons (555);
GenCons test2 = new GenCons (15.25F);
[Link] ();
[Link] ();
}
}
57
Java Generics: Wildcard
• Wildcard is an approach in Generic Programming.
• The ? (question mark) symbol denotes the wildcard. It means unknown (any) type.
• Wildcard can be used as a type of a parameter, field, return type, or local variable.
• However, wildcard is not allowed to use a as a type argument for a generic method
invocation, a generic class instance creation, or a supertype.
58
Wildcard Types
Types of wildcards in Java:
• Upper bounded wildcards,
• Lower Bounded Wildcards, and
• Unbounded Wildcards.
Bounded Types:
• A bounded wildcard states the type argument can be an
upper bound, lower bound, and unbounded.
• It restricts the types of objects which are using in a method.
59
Wildcard: Upper bounded
• The most widely used wildcard is the upper bound.
• Create an upper bound that declares the superclass to specify Type parameter, from which all type
arguments must be derived.
• Upper bounded wildcards decrease the restrictions on a variable.
• It restricts the unknown type to be a specific type or a subtype of that type.
• It is declared with Type variable (wildcard character "?") followed by the extends (in case of, class)
or implements (in case of, interface) keyword, followed by its upper bound.
Syntax:
<T extends superclass>
• T can only be replaced by superclass, or subclasses of superclass.
• Thus, superclass defines upper limit. 60
Wildcard: Upper bounded
• Example: <? extends Number>
• Number class has subclasses like Integer, Float,
import [Link];
double. class Sample <T extends Number> {
// array of Number or subclass
• So, user can call the method of Number class T[] nums;
Sample(T[] obj) {
through any child class object. nums = obj;
}
<Number>
T sum(){
• Works with only class Number, not with its // returns Type parameter
return T;
subclasses. }
Syntax:
<? super subclass>
Example:
<? super Integer>
64
Wildcard: UnBounded
• The unbounded wildcard type represents the list of an unknown type such as List<?>.
This approach can be useful in the following scenarios: -
• When the given method is implemented by the functionality provided in the Object class.
• When code inside the methods not depend on the type parameter.
65
Unbounded: Example
import [Link];
import [Link];
public class Unbounded {
// Generic method to display elements of a list
public static <T> void display(List<T> list) {
for (T element : list) {
[Link](element);
}
}
public static void main(String[] args) {
// Create a list of integers and display its elements
List<Integer> x = [Link](1, 2, 3);
[Link]("Integer values");
display(x);
// Create a list of strings and display its elements
List<String> y = [Link]("One", "Two", "Three");
[Link]("String values");
display(y);
}
} 66
Wildcard in Java Generics Example 2
import [Link].*;
abstract class Shape {
abstract void area ();
}
class Rectangle extends Shape {
void area () {
[Link] ("Area of rectangle");
}
}
class Square extends Shape {
void area () {
[Link] ("Area of square");
}
}
class Main {
//method accepts only child class of Shape
public static void areaShapes (List < ? extends Shape > lists) {
for (Shape s : lists) {
[Link] ();
}
}
public static void main (String args[]) {
List < Rectangle > list1 = new ArrayList < Rectangle > ();
[Link] (new Rectangle ());
List < Square > list2 = new ArrayList < Square > ();
[Link] (new Square ());
areaShapes (list1);
areaShapes (list2);
}}
67
Generics example
import [Link].*;
class GenType
abstract class<Shape
T > {{
private
abstractTvoid
t; area ();
} public T get () {
return
class this.t; extends Shape {
Rectangle
}
void area () {
public void set
[Link] (T t1) {
("Area of rectangle");
this.t
} = t1;
} }
}
class Square extends Shape {
public class()
void area Main{ {
public static <T > boolean
[Link] ("AreaisEqual (GenType < T > g1, GenType < T > g2)
of square"); {
return
} [Link] ().equals ([Link] ());
} }
public
class static
Main { <T extends Comparable < T >> int compare (T t1, T t2) {
return [Link]
//method accepts only (t2);
child class of Shape
}
public static void areaShapes (List < ? extends Shape > lists) {
public static void
for (Shape s : lists) main (String
{ args[]) {
GenType < String
[Link] (); > g1 = new GenType <> ();
[Link]
} ("Hi");
GenType
} < String > g2 = new GenType <> ();
[Link] ("Hi");
public static void main (String args[]) {
boolean
List <isEqual
Rectangle = Main.
> list1< String
= new > isEqual (g1,
ArrayList g2);
< Rectangle > ();
[Link] (isEqual);
[Link] (new Rectangle ());
//above
Liststatement
< Square > can be written
list2 simply as< Square > ();
= new ArrayList
isEqual = [Link]
[Link] (new Square(g1, ());g2);
[Link]
areaShapes (list1); (isEqual);
[Link]
areaShapes (list2); ([Link] ("abc", "abc"));
}}}
} 68
End of Module 5
69