Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Generics
Dr Walid M. Aly
Lecture 5
Generic Types
A generic type is a generic class or interface that is
parameterized over types.
To reference the generic Box class from within your code, you must perform
a generic type invocation, which replaces T with some concrete value, such
as Integer:
– Box<Integer> integerBox = new Box<Integer>();
Compile error
C:\Documents and Settings\Alex Computer\My
Documents\BoxDemo3.java:17: add(java.lang.Integer) in
Box<java.lang.Integer> cannot be applied to
(java.lang.String)
integerBox.add(new String("test"));
9
^
CS244-Lec#5 -Dr Walid M. Aly 15:35
Why Use Generics?
•Elimination of casts.
The following code snippet without generics requires casting:
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);
When re-written to use generics, the code does not require casting:
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0); // no cast
CS244-Lec#5 -Dr Walid M. Aly 15:35 10
Without using Generics in class Box
}
} Exception in thread "main"
java.lang.ClassCastException: java.lang.String
cannot be cast to java.lang.Integer at
BoxDemo2.main(BoxDemo2.java)
If the Box class had been designed with generics in mind, this mistake would have been
caught by the compiler, instead of crashing the application at runtime.
11
CS244-Lec#5 -Dr Walid M. Aly 15:35
The Diamond
• In Java SE 7 and later, you can replace the type arguments required
to invoke the constructor of a generic class with an empty set of
type arguments (< >) as long as the compiler can determine, or
infer, the type arguments from the context.
• This pair of angle brackets, < >, is informally called the diamond.
• For example, you can create an instance of Box<Integer> with the
following statement:
ArrayList class that lets you collect objects, just like an array does. Array lists offer two significant
conveniences:
· Array lists can grow and shrink as needed
· The ArrayList class supplies methods for many common tasks, such as inserting and removing
elements -Dr Walid M. Aly
CS244-Lec#5 15:35 13
Declaring Generic Classes and Interfaces
GenericStack
Interface java.lang.Comparable<T>
public int compareTo(T o)
Compares this object with the specified object for order. Returns a negative integer,
zero, or a positive integer as this object is less than, equal to, or greater than the
specified object.
Throws:
NullPointerException - if the specified object is null
ClassCastException - if the specified object's type prevents it from being compared to this object.
Example:
class Student implements Comparable<Student> {…}
CS244-Lec#5 -Dr Walid M. Aly 15
Example: Class implementing Comparable
import java.lang.Comparable;
class Student implements Comparable<Student>{
private double GPA;
Improves reliability
CS244-Lec#5 -Dr Walid M. Aly 15:35 17 Compile error
Interface java.util.Comparator<T>
A comparison function, which imposes a total ordering on some collection of
objects
Example
public class TestCompartor implements Comparator<Student>{….}
TestCompartor.java
import java.util.Comparator;
public class TestCompartor implements Comparator<Student>{
class Student{
public int compare(Student student1, Student student2)
private double GPA;
{
public Student(double GPA)
if (student1.getGPA()<student2.getGPA())
{
return -1;
this.GPA=GPA;
if(student1.getGPA()>student2.getGPA())
}
return 1
public double getGPA()
return 0;
{
}
return GPA;
public static void main (String [] args){
}
TestCompartor testCompartor=new TestCompartor();
}//end class Student
Student student1=new Student(2);
Student student2=new Student(3.2);
System.out.println(testCompartor.compare(student1,student2));
}
}
The isEven method invokes the intValue method defined in the Integer class through n.
15:35 21
wildcard generic type
? unbounded wildcard, any object, the same as ?
extends Object
? extends E: a bounded wildcard, any object from
class E or any of its unknown sub classes
? Super E: lower-bound wildcard, any object
from class E or any of its unknown super classes
ShowInnerClass
new SuperClassName/InterfaceName() {
// Implement or override methods in superclass or interface
// Other methods if necessary
}
System.out.println("-----------------");
runner.run1(()->
{
//multiple line of codes
System.out.println("Hello There");
System.out.println("Hello There again");
}
);
App2.java
CS244-Lec#5 -Dr Walid M. Aly
Single Abstract Method Interface (SAM)
class Runner {
public void run (Executable e){
interface Executable {
System.out.println("executing code block");
public int execute();
int value= e.execute();
}
System.out.println("Returned Value:"+value);
}}
interface Executable {
public int execute();
}
class Runner {
public void run (Executable e){
System.out.println("executing code block");
int value= e.execute();
System.out.println("Returned Value:"+value); }}
App3.java
CS244-Lec#5 -Dr Walid M. Aly
Getting a return value…..
runner.run(()->
{ //returning a literal value with implicit return
return 7; System.out.println("-------------------------");
} runner.run (()-> 7);
);
public class A {
runner.run(()-> new A().m());
public int m(){return 7;}
}
//passing argument
runner.run((int a)->
{
System.out.println("This is a start of code block passed by Lambda Expression");
System.out.println("Hello There");
return 7+a;
}
);
//passing argument //you can remove the type and java can infer them
runner.run((int a)-> 7+a); runner.run((a)-> 7+a);
App5.java
CS244-Lec#5 -Dr Walid M. Aly
passing multiple argument
class Runner {
public void run(Executable e)
{
System.out.println("executing code block");
int value= e.execute(5,7);
System.out.println("Returned Value:"+value);
}
}
interface Executable {
public int execute(int a, int b);
}
int c=12;
//c=9; compile error
App7.java