Posts

Showing posts from July, 2018

Java Generics - 9. Type Erasure

Image
This is part 9 of the 9 part series on Java Generics  Prev Topic Target Types Topics 1. Introduction 2. Bounding 3. Multiple bounding 4. Generic Methods 5. Wildcards 6. Typed Classes as method parameters 7. Upper and Lower Bounds 8. Target Types 9. Type Erasure Java Generics - Type Erasure Java Generics were created for tight type checking during compile time. Java complier applies the type erasure to the java code. Actually it replaces generic types by:          Bounds for bounded types and Object for all unbounded types          Inserts casting where necessary          Add bridge methods whenever needed The Generics also ensures that no new classes are created by the compiler to achieve these goals. Have a look at the types class called Gen<E> below that is unbounded. It is in fact compiled as the class Gen with th...

Java Generics - 8. Target Types

Image
This is part 8 of the 9 part series on Java Generics  Prev Topic Upper and Lower Bounds Topics 1. Introduction 2. Bounding 3. Multiple bounding 4. Generic Methods 5. Wildcards 6. Typed Classes as method parameters 7. Upper and Lower Bounds 8. Target Types 9. Type Erasure Next Topic Type Erasure Java Generics - Target Types As per java specification – A target type of an expression is the data type that the compiler expects when it is being used. Consider the method createList in the class TypeInference below, that creates the list of 2 elements which are passed in its parameter. public class TypeInference {                      public static <E> List<E> createList(E e1 , E e2 ){               List<E> ...

Java Generics - 7. Upper and Lower Bounds

Image
This is part 7 of the 9 part series on Java Generics  Prev Topic Typed Classes as method parameters Topics 1. Introduction 2. Bounding 3. Multiple bounding 4. Generic Methods 5. Wildcards 6. Typed Classes as method parameters 7. Upper and Lower Bounds 8. Target Types 9. Type Erasure Next Topic Target Types Java Generics - Upper and Lower Bounds This is going to be a really long blog, so please bear with me. Declaring Generic Variables You can also use generics to declare the variables. In other work you can choose which types can be assigned to a variable. The rules are more or less the same as for methods. You cannot define a type variable, like you could for the methods. Thus the declaration below makes no sense.         // invalid        private <E extends Fruit> E var1 = null ;      ...