Module V - OOPS 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 54

Module-5

Collection, overview, 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 –Generic Constructors and Interfaces

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java Collections
• A collection is a data structure that groups multiple elements into a single unit
• Very useful
• store, retrieve and manipulate data

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Collections Framework
• A collections framework is a unified architecture for representing and manipulating
collections
The components of Java Collections Framework:
• Collection Interfaces: form the basis of the framework
- such as lists, sets, and maps
• Implementations Classes: implementations of the collection interfaces
-Array List, HashSet, HashMap
• Utilities - Utility functions for manipulating collections such as sorting, searching…
• The Java Collections Framework also includes: algorithms

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Collections Framework
Hierarchy
Why the Collections Framework
• The Java collections framework provides various data structures and algorithms
that can be used directly.
• We do not have to write code to implement these data structures and algorithms
manually.
• Moreover, the collections framework allows us to use a specific data structure for
a particular type of data. Here are a few examples
• If we want our data to be unique, then we can use the Set interface provided
by the collections framework.
• To store data in key/value pairs, we can use the Map interface.
• The ArrayList class provides the functionality of resizable arrays

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Collections Framework Hierarchy
Hierarchy

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Collection interface
• The Collection interface is the root of the collection hierarchy
• List Interface- The List interface is an ordered collection that allows us to add and
remove elements like an array.
• Set Interface-The Set interface allows us to store elements in different sets similar
to the set in mathematics. It cannot have duplicate elements.
• Java Map Interface- In Java, the Map interface allows elements to be stored in
key/value pairs.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java List
• In Java, the List interface is an ordered collection that allows us to store and
access elements sequentially.
• Classes that implement List-Since List is an interface, we cannot create objects
from it.
• In order to use functionalities of the List interface, we can use these classes
• ArrayList
• LinkedList
• Vector
• Stack

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Methods of List
• add() - adds an element to a list
• addAll() - adds all elements of one list to another
• get() - helps to randomly access elements from lists
• iterator() - returns iterator object that can be used to sequentially access
elements of lists
• set() - changes elements of lists
• remove() - removes an element from the list
• removeAll() - removes all the elements from the list
• clear() - removes all the elements from the list (more efficient than removeAll())
• size() - returns the length of lists
• toArray() - converts a list into an array
• contains() - returns true if a list contains specified element

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


The ArrayList Class
• Java ArrayList class uses a dynamic array for storing the elements.
• ArrayList is a java class implemented using the List interface.
• ArrayList supports dynamic arrays that can grow or shrink as needed.
• In Java, standard arrays are of a fixed length. After arrays are created, they
cannot grow or shrink.
• An ArrayList is a variable-length array of object references. That is, an ArrayList
can dynamically increase or decrease in size.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


The ArrayList Class
Creating ArrayList:
ArrayList<Type> arrayList= new ArrayList<>();

// create Integer type arraylist


ArrayList<Integer> arrayList = new ArrayList<>();

// create String type arraylist


ArrayList<String> arrayList = new ArrayList<>();

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Basic operations on ArrayList
• The ArrayList class provides various methods to perform different operations on
arraylists.
• Add elements
• Access elements
• Change elements
• Remove elements
• Search elements

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Creating and Adding elements to ArrayList
import java.util.ArrayList;

class AL1 {
public static void main(String[] args){

// create ArrayList
ArrayList<String> languages = new ArrayList<>();

// Add elements to ArrayList


languages.add("Java");
languages.add("Python");
languages.add("C++");

System.out.println("ArrayList: " + languages); O/P:ArrayList: [Java, Python, C++]


}
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 12
Access ArrayList Elements
• To access an element from the arraylist, we use get() method of the ArrayList class

import java.util.ArrayList;
class AL1 {
public static void main(String[] args){
ArrayList<String> languages = new ArrayList<>();

languages.add("Java");
languages.add("Python");
languages.add("C++");

System.out.println("Second Element: " + languages.get(1));


}
} O/P: Python

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Change ArrayList Elements
• To change elements of the arraylist, we use set() method

import java.util.ArrayList;
class AL1 {
public static void main(String[] args){
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("C++");
System.out.println("Before: " + languages);
languages.set(2,"Ruby");
System.out.println("After: " + languages);
}}
O/P:
Before: [Java, Python, C++]
After: [Java, Python, Ruby]
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Remove ArrayList Elements
• To remove an element from the arraylist, we can use remove() method.

import java.util.ArrayList;
class AL1 {
public static void main(String[] args){
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("C++");

System.out.println("Before: " + languages);


String str=languages.remove(1);
System.out.println("After: " + languages); O/P:
}} Before: [Java, Python, C++]
After: [Java, C++]
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Search ArrayList Elements
• To search an element in the arraylist, we can use contains() method.

import java.util.ArrayList;

class AL1 {
public static void main(String[] args){

ArrayList<String> languages = new ArrayList<>();

languages.add("Java");
languages.add("Python");
languages.add("C++");
String str="Java"; O/P:
System.out.println("Found: " +languages.contains(str)); Found: true
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Iterator
• Iterator in Java is used in the Collection framework to retrieve elements one by one.
• Iterator object can be created by calling iterator() method present in Collection
interface.

Iterator itr = c.iterator();

• c is collection object.

Methods of Iterator Interface in Java


hasNext(): Returns true if the iteration has more elements.
next(): Returns the next element in the iteration.
remove(): Removes the next element in the iteration. This method can be called only
once per call to next().

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Sum of elements in the ArrayList using Iterator
import java.util.*;

public class iterator {


public static void main(String[] args)
{
int sum=0; Iterator<Integer> itr = al.iterator();
ArrayList<Integer> al = new while (itr.hasNext()) {
ArrayList<>(); int i =
for (int i = 0; i < 10; i++) itr.next();
al.add(i);
sum=sum+i;
System.out.println(al); }
System.out.println("sum of elements in the
arraylist is:"+sum);
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE }
Removing Odd numbers using iterator()
import java.util.*;
public class remove {
public static void main(String[] args)
{
ArrayList<Integer> al = new ArrayList<>();
for (int i = 0; i < 10; i++)
al.add(i);
System.out.println(“Before:”+al);

Iterator<Integer> itr = al.iterator();


while (itr.hasNext()) {
int i = itr.next();
if (i % 2 != 0)
itr.remove();
}
System.out.println(“After:”+al);
}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
For-Each
• It’s commonly used to iterate over an array or a Collections class

Syntax:
for (datatype variable : array)
{
statements using var;
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Average of elements in the ArrayList using for each
import java.util.*;
public class Average {
public static void main(String[] args)
{
int sum=0;
ArrayList<Integer> al = new ArrayList<>();
for (int i = 1; i < 10; i++)
al.add(i);
System.out.println(al);

for(int i:al)
sum=sum+i;

double avg=(double)sum/(al.size());
System.out.println("Average of elements in the arraylist
is:"+avg);
} }Reddy Ch , Sr. Assistant Professor, SCOPE
Dr. Venkata Rami
Sort elements in the ArrayList using sort()
import java.util.*;
public class sort{
public static void main(String[] args)
{
int sum=0;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(8);
al.add(5);
al.add(3);
al.add(70);
al.add(4);
al.add(25);
System.out.println("Before:"+al);
Collections.sort(al);
System.out.println("After:"+al);
int n=al.size();
System.out.println("Max element in the arraylist is:"+al.get(n-1));
}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Java program that creates an ArrayList to store the name, address, and
age of three researchers. The program will display the entire list of
researchers with all the details and display the average age of all the
researchers.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


import java.util.ArrayList; ArrayList<Researcher> al= new ArrayList<>();
class Researcher{ al.add(r1);
String name; al.add(r2);
String address; al.add(r3);
int age;
int totalAge = 0;
Researcher(String name, String address, int age) { int count = 0;
this.name = name; System.out.println("List of Researchers:");
this.address = address; for (Researcher r: al)
this.age = age; {
} System.out.println(r.name +"\t"+r.address+"\t"+ r.age);
} totalAge=totalAge+ r.age;
count++;
public class ResearcherArrayList { }
public static void main(String[] args) double averageAge = (double) totalAge / count;
{ System.out.println("\nAverage Age : " + averageAge);
Researcher r1=new Researcher("Alice", "Maple St", 35); }} List of Researchers:
Researcher r2=new Researcher("Bob", "Oak St", 40); Alice 123 Maple St 35
Researcher r3= new Researcher("Charlie", "Pine St", 45); Bob 456 Oak St 40
Charlie 789 Pine St 45
Average Age of Researchers: 40.0
Write a java program to create an integer type ArrayList named “sum” and add five positive integers to the array
list. Apply the following operations on Sum ArrayList.
1) Print the elements of ArrayList.
2) Print the sum of even and odd numbers of ArrayList
Print the maximum element available on the ArrayList

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


System.out.println("Elements of ArrayList: " + sum);
import java.util.ArrayList;
import java.util.Collections; ArrayList
int evenSum = 0;
public class ArrayListOperations { int oddSum = 0;
public static void main(String[] args) { for (int num : sum) {
// Create an integer type ArrayList named "sum" if (num % 2 == 0) {
ArrayList<Integer> sum = new ArrayList<>(); evenSum += num;
} else {
// Add five positive integers to the ArrayList oddSum += num;
sum.add(10); }
sum.add(25); }
sum.add(30); System.out.println("Sum of even numbers: " +
sum.add(45); evenSum);
sum.add(50); System.out.println("Sum of odd numbers: " +
oddSum);

int maxElement = Collections.max(sum);


System.out.println("Maximum element in the
ArrayList: " + maxElement);
}
}
Java Set Interface
• The Set interface of the Java Collections framework provides the features of
the mathematical set in Java.
• Unlike the List interface, sets cannot contain duplicate elements.
• Classes that implement Set interface
• HashSet
• LinkedHashSet
• EnumSet
• TreeSet

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java Set Interface
Methods of Set
• add() - adds the specified element to the set
• addAll() - adds all the elements of the specified collection to the set
• iterator() - returns an iterator that can be used to access elements of the set
sequentially
• remove() - removes the specified element from the set
• removeAll() - removes all the elements from the set that is present in another specified
set
• retainAll() - retains all the elements in the set that are also present in another specified
set
• size() - returns the length of the set
• toArray() - returns an array containing all the elements of the set
• contains() - returns true if the set contains the specified element

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java HashSet Class
• A HashSet is a collection of unique items, and it is found in the java.util package

Creating a HashSet
HashSet<datatype> name = new HashSet();

Ex:
HashSet<String> names= new HashSet();

HashSet<Integer> numbers= new HashSet();

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java HashSet Class
import java.util.HashSet;
class HS1 {
public static void main(String[] args){
HashSet<String> languages = new HashSet();
//Adding items
languages.add("Java");
languages.add("C");
languages.add("Python");
languages.add("C++");
//Printing elements
System.out.println("Before: " + languages);
// Removing elements
languages.remove("C++");
Output:
// Searching elements Before: [Java, C++, C, Python]
System.out.println("Found: " +languages.contains("C++")); Found: false
//Printing elements After: [Java, C, Python]
System.out.println(“After: " + languages);
}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Set Operations on HashSet
import java.util.HashSet;
class operations {
public static void main(String[] args){
HashSet<Integer> hs1= new HashSet();
hs1.add(1);
hs1.add(3);
hs1.add(6);
HashSet<Integer> hs2= new HashSet();
hs2.add(2);
hs2.add(4);
hs2.add(6);
// hs1.addAll(hs2);
// System.out.println("After union: " +hs1);
//hs1.retainAll(hs2); //Intersection
//System.out.println("After Intersection: " + hs1);
hs1.removeAll(hs2); //Setdifference
System.out.println("After Setdifference: " + hs1);
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Average of elements in the HashSet using for each

import java.util.*;
public class Average {
public static void main(String[] args)
{
int sum=0;
HashSet<Integer> hs = new HashSet();
hs.add(5);
hs.add(10);
hs.add(3);
System.out.println(hs);

for(int i:hs)
sum=sum+i;

double avg=(double)sum/(hs.size());
System.out.println("Average is:"+avg);
}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Java program that creates a HashSet to store the name, author, and
price of three books. The program will display the entire list of
books with all the details and display the average price of all the
books

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


import java.util.*; set.add(b1);
class Book { set.add(b2);
String name, author; set.add(b3);
int price;
Book(String name, String author,int price) int totalPrice = 0,count = 0;
{ System.out.println("List of Books:");
this.name = name;
this.author = author; for (Book b: set)
this.price = price; {
}} System.out.println(b.name + “\t" + b.author + “\t”+ b.price);
totalPrice += b.price;
public class HashSetExample { count++;
public static void main(String[] args) { }
HashSet<Book> set=new HashSet<Book>(); double averagePrice = (double) totalPrice / count;
Book b1=new Book("C","Yashwant ",500); System.out.println("\nAverage Price: " + averagePrice);
Book b2=new Book("OOPS","RNR",400);
Book b3=new Book("OS","Galvin",600);
List of Books:
C Yashwant 500
OS Galvin 600
OOPS RNR 400
Average Price : 500.0
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
HashMap
• HashMap provides the basic implementation of the Map interface of Java.
• HashMap in Java stores the data in (Key, Value) pairs.

Methods of Map:
put(K, V) - Inserts the key K and a value V into the map
get(K) - Returns the value associated with the specified key K.
containsKey(K) - Checks if the specified key K is present in the map or not.
containsValue(V) - Checks if the specified value V is present in the map or not.
remove(K) - Removes the entry from the map represented by the key K.
keySet() - Returns a set of all the keys present in a map.
values() - Returns a set of all the values present in a map.
entrySet() - Returns a set of all the key/value mapping present in a map.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


HashMap
import java.util.*;
public class HM1{
public static void main(String args[]){

HashMap<Integer,String> map=new HashMap();

map.put(1,"Mango");
map.put(2,"Apple");
map.put(3,"Banana");
map.put(4,"Grapes");

System.out.println(map.get(3));
map.remove(4);
System.out.println(map);
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Iterating through HashMap
import java.util.*;
public class HM1{
public static void main(String args[]){
int sum=0;
HashMap<String,Integer> map=new HashMap();
map.put("Java",80);
map.put("Python",90);
map.put("C",70);

for(Map.Entry m : map.entrySet()){
sum=sum+(int)m.getValue();
}
double avg=(double)sum/(map.size());
System.out.println("Average marks is:"+avg);

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java program that creates a Map named "Researcher" to store the name,
address, and age of three researchers. The program will display the
entire list of researchers with all the details and calculate and display the
average age of all the researchers. Traversing elements, calculation, and
display are all done within the main method of the same class

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


import java.util.HashMap;
import java.util.Map; int totalAge = 0,count = 0;
class Researcher { System.out.println("List of Researchers:");
String name,address; for (Map.Entry<String, Researcher> entry : rm.entrySet())
int age; {
Researcher researcher = entry.getValue();
Researcher(String name, String address, int age) { System.out.println(researcher.name + "\t" +
this.name = name; researcher.address + "\t" + researcher.age);
this.address = address; totalAge += researcher.age;
this.age = age; count++;
} }
}

public class ResearcherMapExample { double averageAge = (double) totalAge / count;


public static void main(String[] args) { System.out.println("\nAverage Age : " + averageAge);
}
Map<String, Researcher> rm = new HashMap<>(); }
List of Researchers:
// Add researcher details to the Map Bob Oak St 40
rm.put("R1", new Researcher("Alice", "Maple St", 35)); Charlie Pine St 45
rm.put("R2", new Researcher("Bob", "Oak St", 40)); Alice Maple St 35
rm.put("R3", new Researcher("Charlie", "Pine St", 45));
Average Age of Researchers: 40.0
Create a HashMap containing a list of 10 usernames and their
passwords. Read a username and a password of a user from keyboard
and display appropriate message whether username and password match
with an entry in the HashMap. If username does not exist, get new
username and password from user and add an entry to HashMap.
Moreover, iterate all the entries using for each loop

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


import java.util.HashMap; // Check if username exists
import java.util.Map; if (userCredentials.containsKey(username)) {
import java.util.Scanner; // Check if password matches
if (userCredentials.get(username).equals(password)) {
public class UserAuthentication {
public static void main(String[] args) { System.out.println("Username and password match.");
HashMap<String, String> userCredentials = new HashMap<>(); } else {
userCredentials.put("user1", "password1"); System.out.println("Password does not match.");
userCredentials.put("user2", "password2"); }
userCredentials.put("user3", "password3"); } else {
userCredentials.put("user4", "password4"); System.out.println("Username does not exist. Adding new user.");
userCredentials.put("user5", "password5"); System.out.print("Enter new username: ");
userCredentials.put("user6", "password6");
String newUsername = scanner.nextLine();
userCredentials.put("user7", "password7");
userCredentials.put("user8", "password8"); System.out.print("Enter new password: ");
userCredentials.put("user9", "password9"); String newPassword = scanner.nextLine();
userCredentials.put("user10", "password10"); userCredentials.put(newUsername, newPassword);
System.out.println("New user added.");
Scanner scanner = new Scanner(System.in); }
// Read username and password from the user System.out.println("Current list of users:");
System.out.print("Enter username: ");
for (Map.Entry<String, String> entry : userCredentials.entrySet()) {
String username = scanner.nextLine();
System.out.print("Enter password: "); System.out.println("Username: " + entry.getKey() + ", Password: " +
String password = scanner.nextLine(); entry.getValue());
}}}
Java Generics
• The Java Generics allows us to create a single class, interface, and method
that can be used with different types of data.

Motivation for Generic Programming :


• Generic programming is a programming paradigm that emphasizes writing
code that can work with a variety of data types, rather than being specific to
a single type.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Generic Classes & Constructors
• Java Generics Class is a class that can be used with any type of data.
• Generic classes are classes that are defined with one or more type parameters.
generic constructor:
• A generic constructor is a constructor that is designed to work with multiple types.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Generic Classes & Constructors
class Test<T> { class Demo {
private T item; public static void main(String args[]){
public Test(T item){ Test<String> ob1 = new
this.item = item; Test<String>(“Java");
} System.out.println(ob1.getItem());
public T getItem() {
return item; Test<Integer> ob2 = new
} Test<Integer>(100);
} System.out.println(ob2.getItem());

}
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Generic Classes & Constructors
class Test<T, U> {
T itemT; public class GenericsTest {
U itemU; public static void main(String args[]){
public Test(T itemT, U itemU){ Test<String, Integer> test =
this.itemT = itemT; new Test<String, Integer>("Test",
this.itemU = itemU; 100);
} test.showItemDetails();
public void showItemDetails(){ }
System.out.println("Value of the itemT: " }
+ itemT);
System.out.println("Value of the itemU: "
+ itemU);

}
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Generic Methods
• In Java, generic methods allow you to define methods that can work with different
types of data.

class Test{ class GenericsTest {


//Generics method public static void main(String args[]){
public <T> void showItemDetails(T item){ Test test = new Test();
System.out.println("Value : " + test.showItemDetails(“Java");
item ); test.showItemDetails(100);
}}
}}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Create a Java programme that defines a generic constructor for the "Student" class in order
to initialize the age variable. Create a generic method student_age () to return the age of each
student. Create three "Student" class objects in the "Main" class to send the ages of three
students as parameters. The age for the first student should be supplied as an integer. The age
for the second student should be supplied as a float. Similarly, the age for the third student
should be sent as a double. Finally, call the student_age () method to get and display the ages of
all three students.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


public class Main {
class Student<T> { public static void main(String[] args) {
private T age;
Student<Integer> s1 = new Student<>(20);
public Student(T age) { Student<Float> s2 = new Student<>(21.5f);
this.age = age; Student<Double> s3 = new Student<>(22.75);
}
System.out.println("Student 1 age: " +
public T studentAge() { s1.studentAge());
return age; System.out.println("Student 2 age: " +
} s2.studentAge());
} System.out.println("Student 3 age: " +
s3.studentAge());
}
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Create a Java programme that defines a generic constructor for the "Faculty" class in order
to initialize the salary variable. Create a generic method display () to return the salary of each
faculty member. Create three "Faculty" class objects in the "Main" class to send the salaries of
three faculties as parameters. The pay amount for the first faculty member should be supplied
as an integer. The pay amount for the second faculty member should be supplied as a float.
Similarly, the salary amount for the third faculty should be sent as a double. Finally, call the
display () method to get and display the salaries of all three faculties.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


public class Main {
public static void main(String[] args) {
class Faculty<T> {
private T salary; Faculty<Integer> f1 = new Faculty<>(50000);
Faculty<Float> f2 = new Faculty<>(65000.5f);
public Faculty(T salary) Faculty<Double> f3 = new Faculty<>(80000.75);
{
System.out.println("Faculty 1 salary: $" +
this.salary =
f1.display());
salary;
System.out.println("Faculty 2 salary: $" +
} f2.display());
System.out.println("Faculty 3 salary: $" +
public T display() { f3.display());
return salary; }
} }
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Generic interfaces
• In Java, generic interfaces allow you to create reusable code that can handle multiple data
types.
class Ginterface {
import java.util.*; public static void main(String[] args) {
interface Container<T> { Container<String> ob1 = new MyContainer<>();
void add(T item); ob1.add("Apple");
void print(); ob1.add("Banana");
} ob1.print();
class MyContainer<T> implements Container<T> {
ArrayList<T> al;
public MyContainer() {
Container<Integer> ob2= new MyContainer<>();
al = new ArrayList<>();
} ob2.add(1);
public void add(T item) { ob2.add(2);
al.add(item); ob2.print();
} [Apple, Banana]
public void print() { } [1, 2]
System.out.println(al); }
}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Write a java program to create a generic interface called “Marks”. Create three objects of the
“Student” class which implements “Marks”. Call the “Marks_display” method (abstract) three
times through three different objects by sending marks of three students as the parameter. For
the first student, the marks should be sent as an integer. For the second student, the marks
should be sent as a float. Similarly, for the third student, the marks should be sent as a string.
Finally, call the display() method available in the “Student” class to display the marks of all
the three students.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Generic interfaces
public class Main {
interface Marks<T> { public static void main(String[] args) {
void Marks_display(T marks);
Student<Integer> student1 = new Student<>();
}
Student<Float> student2 = new Student<>();
class Student<T> implements Marks<T> { Student<String> student3 = new Student<>();
private T marks;
student1.Marks_display(85);
@Override student2.Marks_display(92.5f);
public void Marks_display(T marks) { student3.Marks_display("A+");
this.marks = marks; System.out.println("Student 1:");
System.out.println("Marks stored: " + marks); student1.display();
} System.out.println("Student 2:");
student2.display();
public void display() {
System.out.println("Marks: " + marks); System.out.println("Student 3:");
} student3.display();
} }
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Bounded Types
• Bounded types in Java generics allow you to restrict the types that can be used as type
arguments for a generic class or method.

class Demo{
class Box<T extends Number> { public static void main(String args[])
private T value; {
public void setValue(T value) { Box<Integer> intBox = new Box<>();
this.value = value; intBox.setValue(10);
} System.out.println(intBox.getValue());
public T getValue() { Box<Double> doubleBox = new Box<>();
return value; doubleBox.setValue(3.14);
}} System.out.println(doubleBox.getValue());

Box<Double> doubleBox = new Box<>(); //error

}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE

You might also like