generics in java

23
GENERICS IN JAVA BY: Ankit Goyal Sankalp Singh

Upload: kacy

Post on 19-Feb-2016

80 views

Category:

Documents


3 download

DESCRIPTION

Generics In Java. 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. - PowerPoint PPT Presentation

TRANSCRIPT

GENERICS IN JAVA

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.

CONSIDER A CODE SNIPPET

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

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

CODE USING GENERICSList<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

DEFINING SIMPLE GENERICSpublic 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).

THIS IS HOW IT LOOKS LIKE!!

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

UNDERSTANDING GENERICSIs 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!

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>.

WRITING GENERIC CLASSESObjectHolder.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();

}}

CODE USING PREVIOUS GENERIC CLASSObjectHolderClient.javaimport 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());

} }

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

}

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;

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;

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

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 &.

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. 

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. 

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

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

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}

}

THANKS!