Java Generics – Useful Resources ”; Previous Next The following resources contain additional information on Java Generics. Please use them to get more in-depth knowledge on this topic. Useful Links on Java Generics The JavaTM Tutorials − The Java Tutorials are practical guides for programmers who want to use the Java programming language to create applications. JavaTM 2 SDK, Standard Edition − Official site for JavaTM 2 SDK, Standard Edition Free Java Download − Download Java for your desktop computer now! Sun Developer Network − Sun Microsystem”s official website listing down all the API documentation, latest Java Technologies, Books and other resource. Useful Books on Java Generics To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
Category: java Generics
Unbounded Types Erasure
Java Generics – Unbounded Types Erasure ”; Previous Next Java Compiler replaces type parameters in generic type with Object if unbounded type parameters are used. Example Live Demo package com.tutorialspoint; public class GenericsTester { public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); Box<String> stringBox = new Box<String>(); integerBox.add(new Integer(10)); stringBox.add(new String(“Hello World”)); System.out.printf(“Integer Value :%dn”, integerBox.get()); System.out.printf(“String Value :%sn”, stringBox.get()); } } class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } } In this case, java compiler will replace T with Object class and after type erasure,compiler will generate bytecode for the following code. Live Demo package com.tutorialspoint; public class GenericsTester { public static void main(String[] args) { Box integerBox = new Box(); Box stringBox = new Box(); integerBox.add(new Integer(10)); stringBox.add(new String(“Hello World”)); System.out.printf(“Integer Value :%dn”, integerBox.get()); System.out.printf(“String Value :%sn”, stringBox.get()); } } class Box { private Object t; public void add(Object t) { this.t = t; } public Object get() { return t; } } In both case, result is same − Output Integer Value :10 String Value :Hello World Print Page Previous Next Advertisements ”;
Java Generics – No Exception
Java Generics – No Exception ”; Previous Next A generic class is not allowed to extend the Throwable class directly or indirectly. //The generic class Box<T> may not subclass java.lang.Throwable class Box<T> extends Exception {} //The generic class Box<T> may not subclass java.lang.Throwable class Box1<T> extends Throwable {} A method is not allowed to catch an instance of a type parameter. public static <T extends Exception, J> void execute(List<J> jobs) { try { for (J job : jobs) {} // compile-time error //Cannot use the type parameter T in a catch block } catch (T e) { // … } } Type parameters are allowed in a throws clause. class Box<T extends Exception> { private int t; public void add(int t) throws T { this.t = t; } public int get() { return t; } } Print Page Previous Next Advertisements ”;
Java Generics – No Overload
Java Generics – No Overload ”; Previous Next A class is not allowed to have two overloaded methods that can have the same signature after type erasure. class Box { //Compiler error //Erasure of method print(List<String>) //is the same as another method in type Box public void print(List<String> stringList) { } public void print(List<Integer> integerList) { } } Print Page Previous Next Advertisements ”;
Java Generics – Bound Types Erasure ”; Previous Next Java Compiler replaces type parameters in generic type with their bound if bounded type parameters are used. Example Live Demo package com.tutorialspoint; public class GenericsTester { public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); Box<Double> doubleBox = new Box<Double>(); integerBox.add(new Integer(10)); doubleBox.add(new Double(10.0)); System.out.printf(“Integer Value :%dn”, integerBox.get()); System.out.printf(“Double Value :%sn”, doubleBox.get()); } } class Box<T extends Number> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } } In this case, java compiler will replace T with Number class and after type erasure,compiler will generate bytecode for the following code. Live Demo package com.tutorialspoint; public class GenericsTester { public static void main(String[] args) { Box integerBox = new Box(); Box doubleBox = new Box(); integerBox.add(new Integer(10)); doubleBox.add(new Double(10.0)); System.out.printf(“Integer Value :%dn”, integerBox.get()); System.out.printf(“Double Value :%sn”, doubleBox.get()); } } class Box { private Number t; public void add(Number t) { this.t = t; } public Number get() { return t; } } In both case, result is same − Output Integer Value :10 Double Value :10.0 Print Page Previous Next Advertisements ”;
Bounded Type Parameters
Java Generics – Bounded Type Parameters ”; Previous Next There may be times when you”ll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for. To declare a bounded type parameter, list the type parameter”s name, followed by the extends keyword, followed by its upper bound. Example Following example illustrates how extends is used in a general sense to mean either “extends” (as in classes) or “implements” (as in interfaces). This example is Generic method to return the largest of three Comparable objects − Live Demo public class MaximumTest { // determines the largest of three Comparable objects public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; // assume x is initially the largest if(y.compareTo(max) > 0) { max = y; // y is the largest so far } if(z.compareTo(max) > 0) { max = z; // z is the largest now } return max; // returns the largest object } public static void main(String args[]) { System.out.printf(“Max of %d, %d and %d is %dnn”, 3, 4, 5, maximum( 3, 4, 5 )); System.out.printf(“Max of %.1f,%.1f and %.1f is %.1fnn”, 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 )); System.out.printf(“Max of %s, %s and %s is %sn”,”pear”, “apple”, “orange”, maximum(“pear”, “apple”, “orange”)); } } This will produce the following result − Output Max of 3, 4 and 5 is 5 Max of 6.6,8.8 and 7.7 is 8.8 Max of pear, apple and orange is pear Print Page Previous Next Advertisements ”;
Java Generics – Type Erasure ”; Previous Next Generics are used for tighter type checks at compile time and to provide a generic programming. To implement generic behaviour, java compiler apply type erasure. Type erasure is a process in which compiler replaces a generic parameter with actual class or bridge method. In type erasure, compiler ensures that no extra classes are created and there is no runtime overhead. Type Erasure rules Replace type parameters in generic type with their bound if bounded type parameters are used. Replace type parameters in generic type with Object if unbounded type parameters are used. Insert type casts to preserve type safety. Generate bridge methods to keep polymorphism in extended generic types. Print Page Previous Next Advertisements ”;
Upper Bounded Wildcards
Java Generics – Upper Bounded Wildcards ”; Previous Next The question mark (?), represents the wildcard, stands for unknown type in generics. There may be times when you”ll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. To declare a upper bounded Wildcard parameter, list the ?, followed by the extends keyword, followed by its upper bound. Example Following example illustrates how extends is used to specify an upper bound wildcard. Live Demo package com.tutorialspoint; import java.util.Arrays; import java.util.List; public class GenericsTester { public static double sum(List<? extends Number> numberlist) { double sum = 0.0; for (Number n : numberlist) sum += n.doubleValue(); return sum; } public static void main(String args[]) { List<Integer> integerList = Arrays.asList(1, 2, 3); System.out.println(“sum = ” + sum(integerList)); List<Double> doubleList = Arrays.asList(1.2, 2.3, 3.5); System.out.println(“sum = ” + sum(doubleList)); } } This will produce the following result − Output sum = 6.0 sum = 7.0 Print Page Previous Next Advertisements ”;
Java Generics – Guidelines for Wildcard Use ”; Previous Next Wildcards can be used in three ways − Upper bound Wildcard − ? extends Type. Lower bound Wildcard − ? super Type. Unbounded Wildcard − ? In order to decide which type of wildcard best suits the condition, let”s first classify the type of parameters passed to a method as in and out parameter. in variable − An in variable provides data to the code. For example, copy(src, dest). Here src acts as in variable being data to be copied. out variable − An out variable holds data updated by the code. For example, copy(src, dest). Here dest acts as in variable having copied data. Guidelines for Wildcards. Upper bound wildcard − If a variable is of in category, use extends keyword with wildcard. Lower bound wildcard − If a variable is of out category, use super keyword with wildcard. Unbounded wildcard − If a variable can be accessed using Object class method then use an unbound wildcard. No wildcard − If code is accessing variable in both in and out category then do not use wildcards. Example Following example illustrates the above mentioned concepts. Live Demo package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class GenericsTester { //Upper bound wildcard //in category public static void deleteCat(List<? extends Cat> catList, Cat cat) { catList.remove(cat); System.out.println(“Cat Removed”); } //Lower bound wildcard //out category public static void addCat(List<? super RedCat> catList) { catList.add(new RedCat(“Red Cat”)); System.out.println(“Cat Added”); } //Unbounded wildcard //Using Object method toString() public static void printAll(List<?> list) { for (Object item : list) System.out.println(item + ” “); } public static void main(String[] args) { List<Animal> animalList= new ArrayList<Animal>(); List<RedCat> redCatList= new ArrayList<RedCat>(); //add list of super class Animal of Cat class addCat(animalList); //add list of Cat class addCat(redCatList); addCat(redCatList); //print all animals printAll(animalList); printAll(redCatList); Cat cat = redCatList.get(0); //delete cat deleteCat(redCatList, cat); printAll(redCatList); } } class Animal { String name; Animal(String name) { this.name = name; } public String toString() { return name; } } class Cat extends Animal { Cat(String name) { super(name); } } class RedCat extends Cat { RedCat(String name) { super(name); } } class Dog extends Animal { Dog(String name) { super(name); } } This will produce the following result − Cat Added Cat Added Cat Added Red Cat Red Cat Red Cat Cat Removed Red Cat Print Page Previous Next Advertisements ”;
Java Generics – Multiple Type Parameters ”; Previous Next A Generic class can have muliple type parameters. Following example will showcase above mentioned concept. Example Create the following java program using any editor of your choice. GenericsTester.java Live Demo package com.tutorialspoint; public class GenericsTester { public static void main(String[] args) { Box<Integer, String> box = new Box<Integer, String>(); box.add(Integer.valueOf(10),”Hello World”); System.out.printf(“Integer Value :%dn”, box.getFirst()); System.out.printf(“String Value :%sn”, box.getSecond()); Box<String, String> box1 = new Box<String, String>(); box1.add(“Message”,”Hello World”); System.out.printf(“String Value :%sn”, box1.getFirst()); System.out.printf(“String Value :%sn”, box1.getSecond()); } } class Box<T, S> { private T t; private S s; public void add(T t, S s) { this.t = t; this.s = s; } public T getFirst() { return t; } public S getSecond() { return s; } } This will produce the following result. Output Integer Value :10 String Value :Hello World String Value :Message String Value :Hello World Print Page Previous Next Advertisements ”;