1 / 23

Generics In Java

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.

kacy
Download Presentation

Generics In Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Generics In Java BY: Ankit Goyal Sankalp Singh

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

  3. Consider a code snippet List list = new ArrayList(); list.add(new String(“hello”)); String s = (String)list.iterator().next();

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

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

  6. Defining Simple generics public interface List<E>{ void add(E x); Iterator<E> iterator(); } public interface Iterator<E>{ E next(); booleanhasNext(); } In the invocation <E> -Formal type parameters are replaced by Actual type parameters(Integer, String, etc).

  7. This is how it looks like!! public interface List<String>{ void add(String x); Iterator<String> iterator(); }

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

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

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

  11. Code using previous generic class ObjectHolderClient.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()); } }

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

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

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

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

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

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

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

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

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

  22. References • java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf • www.javabeat.net/articles/33-generics-in-java-50-1.html • http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ100

  23. Thanks!

More Related