Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh."— Presentation transcript:

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

2 G ENERICS 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.

3 C ONSIDER A CODE SNIPPET List list = new ArrayList(); list.add(new String(“hello”)); String s = (String)list.iterator().next();

4 P ROBLEM WITH A BOVE CODE Wrong Input: list.add(new Integer(0)); Casting can also lead to run time error. Unecessary Casting: String s = (String)list.iterator().next();

5 C ODE USING GENERICS List list = new ArrayList (); list.add(“hello”); String str = list.iterator().next(); //No need of String st = list.get(0); //Casting list.add(new Integer(0)); // Compilation Error

6 D EFINING S IMPLE GENERICS public interface List { void add(E x); Iterator iterator(); } public interface Iterator { E next(); boolean hasNext(); } In the invocation -Formal type parameters are replaced by Actual type parameters (Integer, String, etc).

7 T HIS IS HOW IT LOOKS LIKE !! public interface List { void add(String x); Iterator iterator(); }

8 U NDERSTANDING G ENERICS Is this code legal! List ls = new ArrayList (); List 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!

9 G ENERAL P OINTS ABOUT G ENERICS.. 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 is a subtype of G.

10 W RITING G ENERIC CLASSES ObjectHolder.java public class ObjectHolder { private O anyObject; public O getObject() { return anyObject; } public void setObject(O anyObject) { this.anyObject = anyObject; } public String toString() { return anyObject.toString(); }

11 C ODE USING PREVIOUS GENERIC CLASS ObjectHolderClient.java import java.net.URL; public class ObjectHolderClient { public static void main(String[] args) throws Exception { ObjectHolder stringHolder = new ObjectHolder (); stringHolder.setObject(new String("String")); System.out.println(stringHolder.toString()); ObjectHolder urlHolder = new ObjectHolder (); urlHolder.setObject(new URL("http://www.javabeat.net")); System.out.println(urlHolder.toString()); }

12 G ENERIC 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 void printType(T anyType) { System.out.println(anyType.getClass().getName()); } public static void main(String[] args) { GenericMethods.printType(String.class); GenericMethods.printType(new String("")); }

13 W ILDCARDS Consider: List strObjects = new ArrayList (); List anotherStrObjects = strObjects; // legal List objects = strObjects; // Compile Error Object someObject = new String(""); //legal SOLUTION! List objects = strObjects;

14 The character '?' is a wild-card character and it stands for any Java type. List anyObjects = null; List integers = new ArrayList (); anyObjects = integers; List doubles = new ArrayList (); anyObjects = doubles;

15 E XCEPTIONS ! 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

16 B OUNDING THE PARAMETRIC TYPES public class AnimalActions 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 &.

17 T WO 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.

18 T YPE 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.

19 H OW ACTUALLY COMPILATION TAKES PLACE List list = new ArrayList (); list.add("Hi"); String x = list.get(0); Is converted to List list = new ArrayList(); list.add("Hi"); String x = (String) list.get(0);

20 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 is translated to type Box, which is called the raw type

21 This means that you can't find out what type of Object a generic class is using at runtime. public class MyClass { 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 }

22 R EFERENCES java.sun.com/j2se/1.5/pdf/ generics - tutorial.pdf www. java beat.net/articles/33- generics-in- java -50-1.html http://www.angelikalanger.com/GenericsFAQ/F AQSections/TechnicalDetails.html#FAQ100

23 T HANKS !


Download ppt "G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh."

Similar presentations


Ads by Google