Amity School of Engineering & Technology (CSE)
Java Generics
Generics Amity School of Engineering & Technology (CSE)
• Java Generics allows us to create a single class,
interface, and method that can be used with different
types of data (objects).
• Generics does not work with primitive types (int, float,
char, etc).
Amity School of Engineering & Technology (CSE)
What is a Generic Class?
• A generic class is a class that can operate on objects of
various types while providing compile-time type safety.
Amity School of Engineering & Technology (CSE)
Defining a Generic Class
class ClassName<T> {
// Class body
}
Amity School of Engineering & Technology (CSE)
Single type parameter
class Solution<T>
{
T data;
public static T getData(){
return data;
}
}
Amity School of Engineering & Technology (CSE)
Generic Class Example
class Box<T> {
private T content;
public void setContent(T content) { this.content =
content;
}
public T getContent()
{ return content;
}
}
Amity School of Engineering & Technology (CSE)
Multiple type parameters
public class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}
Amity School of Engineering & Technology (CSE)
Creating Instances of a Generic Class
GenericClass<Integer> intObj = new GenericClass<>();
GenericClass<String> strObj = new GenericClass<>();
Amity School of Engineering & Technology (CSE)
Generic Method Example
class DemoClass {
// create a generics method
public <T> void genericsMethod(T data) {
System.out.println("Generics Method:");
System.out.println("Data Passed: " + data);
}
}
Contd… Amity School of Engineering & Technology (CSE)
class Main {
public static void main(String[] args) {
// initialize the class with Integer data
DemoClass demo = new DemoClass();
// generics method working with String
demo.<String>genericsMethod("Java Programming");
// generics method working with integer
demo.<Integer>genericsMethod(25);
}
}
Example Amity School of Engineering & Technology (CSE)
class GenericMethodExample {
public static <T> void printArray(T[] array) {
for (T item : array) {
System.out.print(item + " ");
}
System.out.println();
}
}
Contd… Amity School of Engineering & Technology (CSE)
public class Main {
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4, 5};
String[] strArray = {"A", "B", "C"};
GenericMethodExample.printArray(intArray);
GenericMethodExample.printArray(strArray);
}
}
Amity School of Engineering & Technology (CSE)
Advantages of Java Generics
• Code Reusability: we can write code that will work with different
types of data
• Type-Safety: One can hold only a single type of objects in
generics.
• Type Casting Is Not Required: There is no need to typecast.
• Compile -Time Checking: It checks all the errors of datatype
related to generics at the time of compile-time so the issue will
not occur at the time of runtime.
Amity School of Engineering & Technology (CSE)
Bounded Type Parameters: Example
class Calculator<T1 extends Number>{
T1 num1;
T1 num2;
T1 sum(T1 num1,T1 num2){
return (T1) (Double.valueOf(num1.doubleValue()+num2.doubleValue()));
}
}
public class Main {
public static void main(String[] args) {
Calculator <Integer> obj=new Calculator<>();
System.out.println(obj.sum(10,20));
}
}
Amity School of Engineering & Technology (CSE)
Wildcards (?) in Generics
• Wildcards (?) are useful when we want to allow unknown
types.
• Types of Wildcards
– Unbounded Wildcard (<?>)Allows any type.
• Can only read elements but cannot add new elements (except null).
• Useful when the type does not matter.
– Upper Bounded Wildcard (<? extends T>)
• Restricts types to T or subclasses of T.
– Lower Bounded Wildcard (<? super T>)
• Restricts types to T or superclasses of T.
Amity School of Engineering & Technology (CSE)
Unbounded Wildcard (<?>) Example
import java.util.List;
class WildcardExample {
public static void printList(List<?> list) {
for (Object obj : list) {
System.out.print(obj + " ");
}
System.out.println();
}
}
Contd… Amity School of Engineering & Technology (CSE)
import java.util.List;
class WildcardExample {
public static void printList(List<?> list) {
for (Object obj : list) {
System.out.print(obj + " ");
}
System.out.println();
}
}
Amity School of Engineering & Technology (CSE)
Why can't we add elements?
• Since we don't know the exact type (<?> could be
Integer, String, or anything else), adding an element is
unsafe.
Amity School of Engineering & Technology (CSE)
Upper Bounded Wildcard (<? extends T>)
• restricts type to T or its subclasses.
• Used when we need to read elements but not modify
them.
• <? extends Number>
– This means the type can be Number or any subclass of
Number (Integer, Double, Float, etc.).
Example Amity School of Engineering & Technology (CSE)
public static void printNumbers(List<? extends Number>
list) {
for (Number num : list) {
System.out.println(num);
}
}
Contd… Amity School of Engineering & Technology (CSE)
List<Integer> intList = Arrays.asList(10, 20, 30);
List<Double> doubleList = Arrays.asList(1.1, 2.2, 3.3);
printNumbers(intList);
printNumbers(doubleList);
Amity School of Engineering & Technology (CSE)
Why can't we add elements?
• The list might be List<Integer> or List<Double>, but
Java doesn't know for sure. So adding a specific type
(Integer or Double) is unsafe.
Amity School of Engineering & Technology (CSE)
Lower Bounded Wildcard (<? super T>)
• Restricts type to T or its superclasses.
• Used when we need to write (add elements) but don't
need to read specific types.
• <? super Integer>
– This means the type can be Integer or any superclass of
Integer (Number, Object, etc.).
Example Amity School of Engineering & Technology (CSE)
public static void addNumbers(List<? super Integer> list)
{
list.add(100); // Allowed
list.add(200);
}
Contd… Amity School of Engineering & Technology (CSE)
List<Integer> intList = new ArrayList<>();
List<Number> numList = new ArrayList<>();
addNumbers(intList);
addNumbers(numList);
Amity School of Engineering & Technology (CSE)
• Integer num = list.get(0); // Compilation Error!
• Object obj = list.get(0); // Allowed
– Since list might hold Integer, Number, or Object, it is only
safe to retrieve elements as Object.
Amity School of Engineering & Technology (CSE)
When to Use Each Wildcard?
• Use <?> when you just need to iterate over a list but
don’t modify it.
• Use <? extends T> when you need to read elements as
T but don’t modify.
• Use <? super T> when you need to add elements of
type T.
Amity School of Engineering & Technology (CSE)
Generic Interfaces
interface GenericInterface<T> {
void display(T data);
}
class GenericClassImpl<T> implements GenericInterface<T> {
public void display(T data) {
System.out.println("Data: " + data);
}
}
Contd… Amity School of Engineering & Technology (CSE)
public class Main {
public static void main(String[] args) {
GenericClassImpl<Integer> intObj = new GenericClassImpl<>();
intObj.display(100);
GenericClassImpl<String> strObj = new GenericClassImpl<>();
strObj.display("Hello Generics");
}
}
Restrictions Amity School of Engineering & Technology (CSE)
• Cannot Instantiate Generic Types with Primitive Types:
• Cannot Create Instances of Type Parameters:
Contd… Amity School of Engineering & Technology (CSE)
• Cannot Declare Static Fields Whose Types are Type
Parameters:
• Cannot Create Arrays of Parameterized Types:
Exercise Amity School of Engineering & Technology (CSE)
Define a generic class Box<T>, where T is a placeholder
for a data type. The class should have: A private field to
store the item of type T. A constructor to initialize the
item. Getter and setter methods. A method display() to
print the item. In the main method: Create a
Box<Integer> and store a number. Create a Box<String>
and store a string. Display their values.
Amity School of Engineering & Technology (CSE)
• Write a generic method to swap two elements in an
array. Create a generic method swap() that: Takes an
array and two indices. Swaps the elements at those
indices. In the main method: Test the method with an
Integer array. Test the method with a String array.