Sei sulla pagina 1di 43

CS244 Advanced programming Applications

Generics

Dr Walid M. Aly

Lecture 5

CS244-Lec#5 -Dr Walid M. Aly


Why Do You Get a Warning?
public class ShowUncheckedWarning {
public static void main(String[] args) {
java.util.ArrayList list = new java.util.ArrayList();
list.add("Java Programming");
}
}

Compile To understand the compile


with warning on this line, you need to
3 Warnings learn JDK generics.

CS244-Lec#5 -Dr Walid M. Aly 2


Fix the Warning
public class ShowUncheckedWarning {
public static void main(String[] args) {
java.util.ArrayList<String> list =
new java.util.ArrayList<String>();
list.add("Java Programming");
}
}
No compile warning on this line.

CS244-Lec#5 -Dr Walid M. Aly 3


What is Generics?
Generics are a facility of generic programming that was added to
the Java programming language in 2004 as part of J2SE 5.0.

They allow a type or method to operate on objects of various


types while providing compile-time type safety

Generic Types
A generic type is a generic class or interface that is
parameterized over types.

CS244-Lec#5 -Dr Walid M. Aly 4


Generic class
A generic class is defined with the following format:
class name<T1, T2, ..., Tn>
{
/*
...
*/
}
The type parameter section, delimited by angle brackets (<>),
follows the class name. It specifies the type parameters (also
called type variables) T1, T2, ..., and Tn.
Generic Interface are defined in the same way

CS244-Lec#5 -Dr Walid M. Aly 5


Type Parameter Naming Conventions
By convention, type parameter names are single, uppercase
letters. Without this convention, it would be difficult to tell the
difference between a type variable and an ordinary class or
interface name.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections
Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types

CS244-Lec#5 -Dr Walid M. Aly 6


A Generic Class
Generic version of the Box class.
public class Box<T>
{
private T t; // T stands for "Type“
public void add(T t)
{
this.t = t; }
public T get()
{
return t;
}
}
CS244-Lec#5 -Dr Walid M. Aly 15:35 7
Invoking and Instantiating a Generic Type

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>();

public class BoxDemo


{
public static void main(String[] args)
{
Box<Integer> integerBox = new Box<Integer>();
integerBox.add(new Integer(10));
Integer someInteger = integerBox.get(); // no cast!
System.out.println(someInteger);
}
}
CS244-Lec#5 -Dr Walid M. Aly 8
A misuse of class Box is caught at compilation time

public class Box<T> public class BoxDemo3


{ {
private T t; // T stands for "Type“ public static void main(String[] args)
public void add(T t) {
{ Box<Integer> integerBox = new Box<Integer>();
this.t = t; } //a careless programmer
public T get() integerBox.add(new String("test"));
{ …………………………………..
return t; //an innocent programmer
} Integer someInteger = integerBox.get();
} System.out.println(someInteger);
}}

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?

•Stronger type checks at compile time.


A Java compiler applies strong type checking to generic code and issues errors if the code
violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can
be difficult to find.

•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

public class Box { public class BoxDemo2 {


private Object object; public static void main(String[] args) {
Box integerBox = new Box();
public void add(Object object) integerBox.add(new Integer(5));
{ Integer someInteger 1= (Integer)integerBox.get();
this.object = object; ………………..
integerBox.add("10"); a careless programmer!!!!
} ……………………………………
public Object get() { Integer someInteger 2= (Integer)integerBox.get();
return object; System.out.println(someInteger); } }

}
} 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:

Box<Integer> integerBox = new Box<


Box< >();

CS244-Lec#5 -Dr Walid M. Aly 15:35 12


Generic ArrayList in JDK 1.5

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

CS244-Lec#5 -Dr Walid M. Aly 15:35 14


Interface java.lang.Comparable<T>
This interface imposes a total ordering on the objects of each
class that implements it.
This ordering is referred to as the class's natural ordering.
A number of classes in java API implements this interface

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;

public int compareTo(Student srudent){


if (this.GPA<srudent.GPA) return -1;
if (this.GPA>srudent.GPA) return 1;
return 0;}

public Student(double GPA){this.GPA=GPA;}


}//end class Student

public class TestComparable{


public static void main (String [] args){
Student student1=new Student(2);
Student student2=new Student(3.2);
System.out.println (student1.compareTo(student2));
}
} TestComparable.java
CS244-Lec#5 -Dr Walid M. Aly 16
Interface Comparable<T>….
Generic Type

package java.lang; package java.lang;

public interface Comparable { public interface Comparable<T> {


public int compareTo(Object o) public int compareTo(T o)
} }

(a) Prior to JDK 1.5 (b) JDK 1.5

Runtime error Generic Instantiation


Comparable c = new Date(); Comparable<Date> c = new Date();
System.out.println(c.compareTo("red")); System.out.println(c.compareTo("red"));

(a) Prior to JDK 1.5 (b) JDK 1.5

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

public int compare(T o1, T o2)


Compares its two arguments for order. Returns a negative integer, zero, or a positive
integer as the first argument is less than, equal to, or greater than the second.

public boolean equals(Object obj)


Indicates whether some other object is "equal to" this comparator

Example
public class TestCompartor implements Comparator<Student>{….}

TestCompartor.java

CS244-Lec#5 -Dr Walid M. Aly 15:35 18


Example: Class implementing Comparator

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));
}
}

CS244-Lec#5 -Dr Walid M. Aly 19


Bounded Type Parameters
• There may be times when you want to restrict the types that can be
used as type arguments in a parameterized type.
• For example, a method that operates on numbers might only want
to accept instances of Number or its subclasses.
• This is what bounded type parameters are for.
• To declare a bounded type parameter, list the type parameter's
name, followed by the extends keyword, followed by
its upper bound, which in this example is Number.
• in this context, extends is used in a general sense to mean
either "extends" (as in classes) or "implements" (as in
interfaces).

public static double max(GenericStack<? extends Number> stack)

CS244-Lec#5 -Dr Walid M. Aly 15:35 20


Bounded Type Parameters…
public class NaturalNumber<T T extends Integer>
Integer
{
private T n;
public NaturalNumber(T n)
{
this.n = n;
}
public boolean isEven()
{
return n.intValue()
n.intValue() % 2 == 0; } // ...
}

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

CS244-Lec#5 -Dr Walid M. Aly 22


Inner Classes
Inner class: A class is a member of another class.
Advantages: In some applications, you can use an inner
class to make programs simple.
An inner class can reference the data and methods
defined in the outer class in which it nests, so you do
not need to pass the reference of the outer class to the
constructor of the inner class.

ShowInnerClass

CS244-Lec#5 -Dr Walid M. Aly 23


Inner Classes, cont.

CS244-Lec#5 -Dr Walid M. Aly 24


Inner Classes (cont.)
An inner class supports the work of its containing outer class and
is compiled into a class named
OuterClassName$InnerClassName.class.

For example, the inner class InnerClass in OuterClass is compiled


into OuterClass$InnerClass.class.

CS244-Lec#5 -Dr Walid M. Aly 25


Inner Classes (cont.)
An inner class can be declared public, protected,
or private subject to the same visibility rules
applied to a member of the class.
An inner class can be declared static.
A static inner class can be accessed using the outer
class name.
A static inner class cannot access nonstatic members
of the outer class

CS244-Lec#5 -Dr Walid M. Aly 26


Anonymous Inner Classes
An anonymous inner class is an inner class without a name
An anonymous inner class must always extend a superclass or
implement an interface, but it cannot have an explicit extends
or implements clause.
An anonymous inner class must implement all the abstract
methods in the superclass or in the interface.
An anonymous inner class uses the no-arg constructor from its
superclass to create an instance.
An anonymous inner class is compiled into a class named
OuterClassName$n.class. For example, if the outer class Test
has two anonymous inner classes, these two classes are
compiled into Test$1.class and Test$2.class.

CS244-Lec#5 -Dr Walid M. Aly 27


Anonymous Inner Classes (cont.)
An anonymous inner class is an inner class without a
name. It combines declaring an inner class and
creating an instance of the class in one step. An
anonymous inner class is declared as follows:

new SuperClassName/InterfaceName() {
// Implement or override methods in superclass or interface
// Other methods if necessary
}

CS244-Lec#5 -Dr Walid M. Aly 28


Example on Anonymous class
class A
{
A(){
System.out.println("An object is created from A");
m();
}
void m(){System.out.println("inside method m in class A ");}
}
class AnonyInnerDemo
{
public static void main (String [] args)
{
new A(){
void m(){System.out.println("inside method m in Anonymous ");}
};
}
}

CS244-Lec#5 -Dr Walid M. Aly 29


lambda expressions
• Lambda expression is a new feature in Java 8.
Lambda expressions can be viewed as an
anonymous method with a concise syntax.
• Lambda expression facilitates functional
programming

CS244-Lec#5 -Dr Walid M. Aly


Basic Syntax for a Lambda Expression
The basic syntax for a lambda expression is either
(type1 param1, type2 param2, ...) -> expression
or
(type1 param1, type2 param2, ...) -> { statements; }

1. The data type for a parameter may be explicitly declared or implicitly


inferred by the compiler.
2. The parentheses can be omitted if there is only one parameter without
an explicit data type.

CS244-Lec#5 -Dr Walid M. Aly 31


Traditional way using outer class
public interface Executable class A implement Executable
{ {
public void execute(); public void execute(){
} System.out.println("Hello");}$
}

public class Runner {


public void run1(Executable e)
{
System.out.println("executing code block");
e.execute();
}
}

public static void main(String[] args) {


Runner runner=new Runner();
A a1=new A();
runner.run1( a);
}

CS244-Lec#5 -Dr Walid M. Aly


Traditional way using anonymous classes
public interface Executable
{
public void execute();
}
public class Runner {
public void run1(Executable e)
{
System.out.println("executing code block");
e.execute();
}
}
public static void main(String[] args) {
Runner runner=new Runner();
runner.run1(
new Executable(){
public void execute(){System.out.println("Hello There");
}
}
);
System.out.println("-----------------");
} App1.java
CS244-Lec#5 -Dr Walid M. Aly
Using Lambda Expression
runner.run1(()-> System.out.println("Hello There"));

System.out.println("-----------------");

runner.run1(()->
{
//multiple line of codes
System.out.println("Hello There");
System.out.println("Hello There again");

}
);

• Lambda expressions are associated with interfaces with single


methods
• This interface is called a functional interface

App2.java
CS244-Lec#5 -Dr Walid M. Aly
Single Abstract Method Interface (SAM)

• Lambda expressions are associated with interfaces with single


methods
• The statements in the lambda expression is all for that method. If it
contains multiple methods, the compiler will not be able to compile
the lambda expression. So, for the compiler to understand lambda
expressions, the interface must contain exactly one abstract
method. Such an interface is known as a functional interface, or a
Single Abstract Method (SAM) interface.

CS244-Lec#5 -Dr Walid M. Aly 35


Getting a return value with traditional way

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);
}}

public class App3 {


public static void main(String[] args) {
Runner runner=new Runner();
//traditional way to return data
runner.run( new Executable(){
public int execute(){
System.out.println("Hello There");
return 7;}
} );
System.out.println("-------------------------");
}}
App3.java
CS244-Lec#5 -Dr Walid M. Aly
Getting a return value using Lambda expression
public class App3 {
public static void main(String[] args) {
Runner runner=new Runner();
runner.run(()->
{
System.out.println("This is a start of code block passed by Lambda Expression");
System.out.println("Hello There");
return 7;
} );
}}

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;}
}

CS244-Lec#5 -Dr Walid M. Aly


Passing arguments to the block of code
public void run(Executable e) {
interface Executable {
System.out.println("executing code block");
public int execute(int a);
int value= e.execute(5);
}
System.out.println("Returned Value:"+value);
}

//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);

//you can remove the type and parenthesis


runner.run( a-> 10+a); App4.java
CS244-Lec#5 -Dr Walid M. Aly
Declaring type to remove ambiguity
interface Executable { class Runner {
public int execute(int a); public void run(Executable e)
} {int value= e.execute(5);}

interface StringExecutable { public void run(StringExecutable e)


public String execute(String a); { String value= e.execute("Hello"); }
} }

// runner.run((a)-> 70+a); //compile error reference to run is ambiguous

// you have to mention type to remove ambiguity


runner.run((int a)-> 70+a);
runner.run((String a)-> a+" "+"Java");

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);
}

//passing multiple argument


runner.run((a,b)-> a+b);
App6.java
CS244-Lec#5 -Dr Walid M. Aly
Accessing Local Variables
• local variables referenced from a lambda expression
must be final or effectively final
• Lambda expressions can also define variables in their
scope

int c=12;
//c=9; compile error

//passing multiple argument


runner.run((a,b)-> a+b+c);

App7.java

CS244-Lec#5 -Dr Walid M. Aly


References
• http://www.tutorialspoint.com/java8/java8_lambda_expressi
ons.htm

CS244-Lec#5 -Dr Walid M. Aly 43

Potrebbero piacerti anche