g enerics i n j ava by: ankit goyal sankalp singh

23
GENERICS IN JAVA BY: Ankit Goyal Sankalp Singh

Upload: ada-harris

Post on 05-Jan-2016

220 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

GENERICS IN JAVA

BY: Ankit Goyal

Sankalp Singh

Page 2: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

GENERICS

The feature of Generics in Java allows Applications to create classes and objects that can operate on any defined types.

It prevents un-necessary casting being done in the Application code and prevents any wrong data-type being used.

Page 3: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

CONSIDER A CODE SNIPPET

List list = new ArrayList();list.add(new String(“hello”));String s = (String)list.iterator().next();

Page 4: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

PROBLEM WITH ABOVE CODE

Wrong Input:list.add(new Integer(0));Casting can also lead to run time error.

Unecessary Casting:String s = (String)list.iterator().next();

Page 5: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

CODE USING GENERICS

List<String> list = new ArrayList<String>();

list.add(“hello”);String str = list.iterator().next(); //No need of String st = list.get(0); //Casting

list.add(new Integer(0)); // Compilation Error

Page 6: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

DEFINING SIMPLE GENERICS

public interface List<E>{ void add(E x); Iterator<E> iterator(); } public interface Iterator<E>{E next();boolean hasNext();}

In the invocation <E> -Formal type parameters are replaced by Actual type parameters(Integer, String, etc).

Page 7: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

THIS IS HOW IT LOOKS LIKE!!

public interface List<String>{ void add(String x); Iterator<String> iterator(); }

Page 8: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

UNDERSTANDING GENERICS

Is this code legal!

List<String> ls = new ArrayList<String>();List<Object> lo = ls; //lo used as an alias to ls

Question: Is a List of String a List of Object??

lo.add(new Object());String s = ls.get(0); // attempts to assign an

object to a string!

Page 9: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

GENERAL POINTS ABOUT GENERICS..

Previous code gives compile time error.

In general, if Foo is a subtype(subclass or subinterface) of Bar, and G is some generics type declaration, it is not the case that G<Foo> is a subtype of G<Bar>.

Page 10: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

WRITING GENERIC CLASSES

ObjectHolder.java

public class ObjectHolder<O> {

private O anyObject;

public O getObject() {

return anyObject;

}

public void setObject(O anyObject) {

this.anyObject = anyObject;

}

public String toString() {

return anyObject.toString();

}

}

Page 11: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

CODE USING PREVIOUS GENERIC CLASSObjectHolderClient.java

import java.net.URL;

public class ObjectHolderClient

{

public static void main(String[] args) throws Exception

{

ObjectHolder<String> stringHolder = new ObjectHolder<String>();

stringHolder.setObject(new String("String")); System.out.println(stringHolder.toString());

ObjectHolder<URL> urlHolder = new ObjectHolder<URL>(); urlHolder.setObject(new URL("http://www.javabeat.net")); System.out.println(urlHolder.toString());

}

}

Page 12: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

GENERIC METHODS A Generic class containing a type parameter affects the

entire class, but a generic method containing one or more type parameters affects that particular method only.

Non-generic class can contain a mixture of generic and non-generic methods.

public class GenericMethods {

static <T> void printType(T anyType)

{

System.out.println(anyType.getClass().getName());

}

public static void main(String[] args) {

GenericMethods.printType(String.class); GenericMethods.printType(new String(""));

}

}

Page 13: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

WILDCARDS Consider:

List<String> strObjects = new ArrayList<String>();

List<String> anotherStrObjects = strObjects; // legal

List<Object> objects = strObjects; // Compile Error

Object someObject = new String(""); //legal

SOLUTION!

List<?> objects = strObjects;

Page 14: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

The character '?' is a wild-card character and it stands for any Java type.

List<?> anyObjects = null;

List<Integer> integers = new ArrayList<Integer>();

anyObjects = integers;

List<Double> doubles = new ArrayList<Double>();

anyObjects = doubles;

Page 15: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

EXCEPTIONS!

Since the type parameter for the reference anyObjects is '?', no objects can be added to the collection, not even java.lang.Object

anyObjects.add(new Integer(1)); // Won’t compile

anyObjects.add(new Double(1.0)); // Wont compile

Null is an Exception to that.

anyObjects.add(null); // This will compile

Page 16: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

BOUNDING THE PARAMETRIC TYPES

public class AnimalActions<A extends Animal & Sleepable & Runnable & Eatable>

Only extends keyword is used for both class as well the interface and not the implements keyword.

If we want the parametric type to confirm by more than one classes or interfaces, then every types should be separated by the symbol &.

Page 17: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

TWO CHOICES FOR COMPILER

Code specialization- The compiler generates a new representation for every instantiation of a generic type or method. For instance, the compiler would generate code for a list of integers and additional, different code for a list of strings, a list of dates, a list of buffers, and so on.

Code sharing. The compiler generates code for only one representation of a generic type or method and maps all the instantiations of the generic type or method to the unique representation, performing type checks and type conversions where needed. 

Page 18: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

TYPE ERASURE

A process that maps a parameterized type (or method) to its unique byte code representation by eliding type parameters and arguments.

The compiler generates only one byte code representation of a generic type or method and maps all the instantiations of the generic type or method to the unique representation. This mapping is performed by type erasure. 

Page 19: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

HOW ACTUALLY COMPILATION TAKES PLACE

List<String> list = new ArrayList<String>();

list.add("Hi");String x = list.get(0);

Is converted to

List list = new ArrayList();list.add("Hi");String x = (String) list.get(0);

Page 20: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method.

To maintain binary compatibility with Java libraries and applications that were created before generics.

For instance, Box<String> is translated to type Box, which is called the raw type

Page 21: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

This means that you can't find out what type of Object a generic class is using at runtime.

public class MyClass<E> { public static void myMethod(Object item) {

if (item instanceof E) { …………….. //Compiler error

}

E item2 = new E(); //Compiler error

E[] iArray = new E[10];//Compiler error}

}

Page 23: G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh

THANKS!