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

Generics

Uploaded by

Ziyad Mohammed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Generics

Uploaded by

Ziyad Mohammed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Chapter 1

Generics

Advanced Programming - Generics 1


1. Introduction
➢ Generics - introduced by JDK5
➢ Designed to extend Java's type system to allow a class, interface or
method to operate on objects of various types while providing compile-
time type safety".
➢ Enables us to create classes, interfaces, and methods that will work
with different kinds of data.
➢ Generic classes, interfaces, and methods declare type parameter/s in
their definition
➢ e.g. class MyClass<T> {} //Generic class
interface MyInterface<T> {} //Generic interface
public <T> void MyMethod(T obj) {} //Generic method
 T is called type parameter
Advanced Programming - Generics 2
1. Introduction
➢ Type parameters are used as a placeholder for the actual type of data
that is being operated up on.
➢ Using generics, it is possible to create a single class, interface, or
method, that automatically works with different types of data.
➢ Generics does not work with primitive data types.
✓ Type parameters can represent only reference types—not primitive types
✓ Type arguments passed to type parameter can not be primitive types.

Advanced Programming - Generics 3


2. Generic Class
➢ A generic class is a class with one or more type parameters.
➢ Defined as: class className <type-param-list> { ... }
➢ Objects generic classes are instantiated as:
` className <type-arg-list> varName = new className<> (arg-list)
➢ Generic classes and interfaces are collectively known as generic types.
➢ Each generic type defines a set of parameterized types,
➢ Let List is a generic class
✓ List<E> is a generic type, E is type parameter.
✓ List<String> is a parametrized type, String is actual type parameter
or type argument.
✓ List is a raw type
Advanced Programming - Generics 4
2. Generic Classes
➢ e.g. the following program defines four classes.
➢ Each of the first three classes define key value pair
➢ The fourth class uses the first three classes.
✓ class Pair0 is non-generic, and the keys and values are only Integers.
 To have key value pair of another data type - define another class
✓ Pair1 is a generic class with one type parameter.
 Key and value can be any type, but same type.
✓ Pair2 is a generic class with two type parameters
 Key and value can be any type - can be different data types.

Advanced Programming - Generics 5


2. Generic Classes - Example
1 class Pair0 { //non- generic class
2 Integer key, value;
3 public Pair0(Integer key, Integer value){
4 this.key = key;
5 this.value = value;
6 }
7 void setKey(Integer key){ this.key = key; }
8 Integer getKey(){ return key; }
9 }

Advanced Programming - Generics 6


2. Generic Classes - Example
1 class Pair1<T>{ // generic class with one type parameter
2 T key, value; // member variables of type T
3 public Pair1(T key, T value) { // local variables of type T
4 this.key = key;
5 this.value = value;
6 }
7 void setKey(T key){ this.key = key;}
8 T getValue(){ return value; } //return type T
9 }

Advanced Programming - Generics 7


2. Generic Classes - Example
1 class Pair2<K, V> { // A generic class with two type parameters.
2 K key; //type parameters used to difine member variables
3 V value;
4 public Pair2(K key, V value){ this.key = key; this.value = value; }
5 void setKey(K key) { this.key = key; }
6 K getKey() { return key; } //type parameters as return types
7 void setvalue (V value) { this.value = value; }
8 V getValue() { return value; }
9 }

Advanced Programming - Generics 8


2. Generic Classes - Example
1 public class MyPairs{
2 public static void main(String [] args){
3 Pair0 p0 = new Pair0(9, 20);
4 Pair1<Integer> pi = new Pair1<>(9, 20);
5 Pair1<String> ps = new Pair1<String>("country", "Ethiopia");
6 Pair2<Integer, String> pis = new Pair2<>(251, "Ethiopia");
7 Pair2<String, Integer> psi = new Pair2<>("Ethiopia", 251);
8 System.out.println(p2.getValue());
9 }
10 }

Advanced Programming - Generics 9


3. Generic Interface
➢ Specified just like generic classes.
➢ e.g,
interface Int1 <T> { ... }
interface Int3 <T extends Number> { ... }
interface Int2 <T extends Comparable<T>> { ...

➢ A class that implements a generic interface must also be generic,

class Class1<T> implements Int1<T>{ ... }


class Class2<T extends Number> implements Int2<T>{ ... }
//we can use subtype of Number as uper bound
class Class3<T extends Integer> implements Int2<T>{ ... }
class Class4<T extends Comparable<T>> implements Int3<T>{ ... }

Advanced Programming - Generics 10


3. Generic Interface
➢ The generic class can have other type parameters.

class Classt5 <T, E> implements Int1<T>{ ... }


class Classy6 <T> implements Int1<T, E> { ... } // Error
➢ If a class implements a specific type of generic interface, then the
implementing class does not need to be generic.

class Class7 implements Int1<Object> {}


class Class8 implements Int1<T> {} //Error
class Class9 implements Int1<Integer>{}
class Class10 implements Int1<String>{}

Advanced Programming - Generics 11


4. Generic Methods
➢ Generic method - A method with one or more type parameter.
➢ Type parameters
✓ precedes the method’s return type
✓ can be used to declare the return type, parameters and local variables.

1 public static <T> T myMethod(T obj1) { //used to declare method `



//parameter and return type
3 T obj2; //used to declare local variable
4 obj2 = obj1;
5 return obj2;
6 }

Advanced Programming - Generics 12


4. Generic Methods
1 class Test{ //non-generic class
2 static <T> T findMiddle(T [ ] arr ) { //generic metthod.
3 return arr[arr.length/2];
4 }
5 public static void main(String [] args){
6 Integer[] a1 = {1, 2, 4, 6, 7};
7 String [] a2 = {"Java", "C#", "C++"};
8 System.out.println(findMiddle(a1)); //type argument - Integer
9 System.out.println(findMiddle(a2)); //String is type argument
10 }}

Advanced Programming - Generics 13


5. Bounded Types
➢ Bounded types limit the parameter types that may be applied to a
generic type.
➢ A bound is a constraint on the type of a type parameter and use the
extends keyword
➢ In the preceding examples, the type parameters could be replaced by
any class type.
➢ In bounded types, the type parameters could be replaced by any
subclass of bound class type.
➢ e.g. for a class, defined as: class C1 <T extends K> { … }
✓ The upper bound, K declares the superclass from which all type arguments
must be derived.

Advanced Programming - Generics 14


5. Bounded Types - Example
1 //This method returns the average of array of numbers as Double.
2 static <T extends Number> Double findAvg(T [] arr){
3 //T subclass of abstract class Number.
4 Double sum = 0.0;
5 for(int i = 0; i<arr.length; i++)
6 sum+= arr[i].doubleValue();
7 //doubleValue is a method of Number class and
8 //returns the specified value as double
9 return sum/arr.length;
10 }
Advanced Programming - Generics 15
5. Bounded Types - Example
1 static <T extends Comparable<T>> T findMax(T [] arr){
2 //T can be any class that implements interface Comparable. i.e only objects
3 //of classes that implement Comparable<T> can be used with this method.
4 T max = arr[0];
5 for(int i = 1; i < arr.length; i++){
6 if(arr[i].compareTo(max) > 0)
7 max = arr[i];
8 } //compareTo is a method of Comparable that returns -1, 0. or 1
10 return max;
11 }
Advanced Programming - Generics 16
5. Bounded Types - Example
1 public static void main(String args[]) {
2 Integer [] ai = {23, 98, 12, 4, 29};
3 String [] as = {"Adama", "Addis Ababa", "Modjo", "Hawassa"};
4 System.out.println(findAvg(ai));//Ok, Integer is a subclass of Number
5 System.out.println(findMax(ai));//OK, Integer implements Comparable
6 System.out.println(findMax(as));//Ok, String implements Comparable
7 System.out.println(findAvg(as));//error.String is not subclass of Number
8 }

Advanced Programming - Generics 17


6. Wildcard Types
➢ Use wildcard when you don’t know or care what the actual type
parameter is.
➢ Three types
✓ Unbounded
✓ Upper bounded
✓ Lower bounded
➢ We can’t use type parameters with the lower bound.
➢ Furthermore, type parameters can have multiple bounds, while
wildcards can’t.
<T extends Object & Comparable<T>>
➢ Bounded wildcards are used to increase API flexibility.
Advanced Programming - Generics 18
6. Wildcard Types - Unbounded
➢ Used when a method doesn't really care about the actual type.
✓ any type (Object) is accepted as argument type.
➢ The following method prints list of any type, List<String> List<Float>
1 public void print3(List<?> list){
2 for(Object o : list)
3 System.out.println(o);
4 }
➢ The following method returns size of list of any type.
1 public int size(List<?> list){
2 int count = 0;
3 for(Object obj : list) count++;
4 return count;
5 }
Advanced Programming - Generics 19
6. Wildcard Types - Upper-Bounded
➢ In generics, parameterized types are invariant.
✓ e.g. List<Integer> and List<Number> are not related like class Integer and
class Number are.
✓ Let us define a generic method that sum up list of Number as:
public static double sum(List<Numer> { … }
✓ We can not pass List<Integer> to this method as argument.
 b/c List<Integer> is not a subtype of List<Number> or they are incompatible
✓ If we redefine the method as:

public double sum(List<? extends Numer> { … }//upper bounded wildcard

✓ Then we can call the method with a list of any subtype of Number class: like
List<Integer>, List<Float>, ...
Advanced Programming - Generics 20
6. Wildcard Types - Lower-Bounded
➢ Specifies the lower class in the hierarchy that can be used as a generic type.
✓ It is expressed using the super keyword.
➢ This type of bound can be used only with a wildcard
✓ Type parameters don’t support lower bound.
 <T super K> - Not supported
 <? super K> - supported

➢ Let us define a generic method that adds a numbers to a list as:


static void add(List<Integer> list, Integer n){
list.add(n);
}
✓ Integer can be added to a list of any super type of Integer, like List<Number>
✓ But we can’t call method add with list of any super type of Integer
Advanced Programming - Generics 21
6. Wildcard Types - Lower-Bounded
✓ If we redefine method add with lower bounded wildcard argument as:

static void add(List<? extends Integer> list, Integer n){


list.add(n);
}
✓ We can call method add using the list of Integer and all of its super types
(Number or Object).
➢ Which wildcard type to use?
✓ If a parameterized type represents a T producer, use <? extends T>.
✓ If it represents a T consumer, use <? super T>.
✓ PECS stands for producer-extends, consumer-super.

Advanced Programming - Generics 22


6. Wildcard Types - Example
Consider the following class that has a member variable s of type Set<E>
1 public class MySet<E>{
2 Set<E> s;
3 public MySet(){
4 s= new HashSet<>();
5 }
6 }
1. Let us add a method to MySet class that receives list of elements and
add them all to set s as follows.
1 public void addAll(List<E> src){
2 for(E e : src)
3 s.add(e);
4 }

Advanced Programming - Generics 23


6. Wildcard Types - Example
The program will not be compiled if we call method addAll as:
MySet<Number> msn = new MySet<>(); //msn is Set of Numbers
List<Integer> li = new ArrayList<>(); //li is list of Integers
msn.addAll(li); //error, List<Integer> & List<Number> are incompatible
If we rewrite method addAll using wildcard as:
1 public void addAll(List<? extends E> src){
2 for(E e : src)
3 s.add(e);
4 }

We can pass list of Integer types as arguments to it.


MySet<Number> msn = new MySet<>(); //msn is Set of Numbers
List<Integer> li = new ArrayList<>(); //li is list of Integers
msn.addAll(li); //ok, addAll expects list of subtype of Number.
Advanced Programming - Generics 24
6. Wildcard Types - Example
2. Let us add a method to MySet class that adds all elements of set s to a
list.
1 public void getAll(List<E> dest){
2 Iterator<E> i = s.iterator();
3 while(i.hasNext())
4 dest.add(i.next());
5 System.out.println(dest);
6 }

The program will not be compiled if we call this method as:


MySet<Integer> msi = new MySet<>(); // msi set of Integer
List<Number> ln = new ArrayList<>(); // ln List of Number
msi.getAll(ln); //error, b/c getAll() expects only list of Integer

Advanced Programming - Generics 25


6. Wildcard Types - Example
If we rewrite the method using wildcard as:
public void getAll(List<? super E> dest){
Iterator<E> i = s.iterator();
while(i.hasNext())
dest.add(i.next());
System.out.println(dest);
}
We can call it as follows
MySet<Integer> msi = new MySet<>();// msi set of Integer
List<Number> ln = new ArrayList<>();// ln List of Numer
msi.getAll(ln);//Ok, b/c getAll() expects list of any super type of Integer

Advanced Programming - Generics 26


7. Generic Restrictions
➢ Generic types can not be instantiated.
1 class MyClass<T>{
2 T o;
3 public MyClass(){
4 o = new T();//Illegal
5 }
6 }
➢ No static member can use a type parameter declared by the enclosing
class.
1 lass MyClass<T>{
2 static T o; //error
3 static T getObj(){ //error
4 return obj;
5 }
6 }
Advanced Programming - Generics 27
7. Generic Restrictions
➢ you cannot instantiate an array whose element type is a type parameter.
1 class MyClass<T> {
2 T [] elements;
3 public MyClass() {
4 elements = new T[10]; //Error
5 }
6 }
➢ A generic class cannot extend Throwable.
✓ you cannot create generic exception classes.

Advanced Programming - Generics 28

You might also like