Java Generics – No Static field

Java Generics – No Static field ”; Previous Next Using generics, type parameters are not allowed to be static. As static variable is shared among object so compiler can not determine which type to used. Consider the following example if static type parameters were allowed. Example 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)); printBox(integerBox); } private static void printBox(Box box) { System.out.println(“Value: ” + box.get()); } } class Box<T> { //compiler error private static T t; public void add(T t) { this.t = t; } public T get() { return t; } } As stringBox and integerBox both have a stared static type variable, its type can not be determined. Hence static type parameters are not allowed. Print Page Previous Next Advertisements ”;

Java Generics – Methods Erasure

Java Generics – Generic Methods Erasure ”; Previous Next Java Compiler replaces type parameters in generic type with Object if unbounded type parameters are used, and with type if bound parameters are used as method parameters. 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”)); printBox(integerBox); printBox1(stringBox); } private static <T extends Box> void printBox(T box) { System.out.println(“Integer Value :” + box.get()); } private static <T> void printBox1(T box) { System.out.println(“String Value :” + ((Box)box).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”)); printBox(integerBox); printBox1(stringBox); } //Bounded Types Erasure private static void printBox(Box box) { System.out.println(“Integer Value :” + box.get()); } //Unbounded Types Erasure private static void printBox1(Object box) { System.out.println(“String Value :” + ((Box)box).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 instanceOf

Java Generics – No instanceOf ”; Previous Next Because compiler uses type erasure, the runtime does not keep track of type parameters, so at runtime difference between Box<Integer> and Box<String> cannot be verified using instanceOf operator. Box<Integer> integerBox = new Box<Integer>(); //Compiler Error: //Cannot perform instanceof check against //parameterized type Box<Integer>. //Use the form Box<?> instead since further //generic type information will be erased at runtime if(integerBox instanceof Box<Integer>) { } Print Page Previous Next Advertisements ”;

Generics – Unbounded Wildcards

Java Generics – Unbounded Wildcards ”; Previous Next The question mark (?), represents the wildcard, stands for unknown type in generics. There may be times when any object can be used when a method can be implemented using functionality provided in the Object class or When the code is independent of the type parameter. To declare a Unbounded Wildcard parameter, list the ? only. Example Following example illustrates how extends is used to specify an unbounded wildcard. Live Demo package com.tutorialspoint; import java.util.Arrays; import java.util.List; public class GenericsTester { public static void printAll(List<?> list) { for (Object item : list) System.out.println(item + ” “); } public static void main(String args[]) { List<Integer> integerList = Arrays.asList(1, 2, 3); printAll(integerList); List<Double> doubleList = Arrays.asList(1.2, 2.3, 3.5); printAll(doubleList); } } This will produce the following result − Output 1 2 3 1.2 2.3 3.5 Print Page Previous Next Advertisements ”;

Java Generics – Generic Map

Java Generics – Map ”; Previous Next Java has provided generic support in Map interface. Syntax Set<T> set = new HashSet<T>(); Where set − object of Set Interface. T − The generic type parameter passed during set declaration. Description The T is a type parameter passed to the generic interface Set and its implemenation class HashSet. Example Create the following java program using any editor of your choice. Live Demo package com.tutorialspoint; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class GenericsTester { public static void main(String[] args) { Map<Integer,Integer> integerMap = new HashMap<Integer,Integer>(); integerMap.put(1, 10); integerMap.put(2, 11); Map<String,String> stringMap = new HashMap<String,String>(); stringMap.put(“1”, “Hello World”); stringMap.put(“2″,”Hi World”); System.out.printf(“Integer Value :%dn”, integerMap.get(1)); System.out.printf(“String Value :%sn”, stringMap.get(“1”)); // iterate keys. Iterator<Integer> integerIterator = integerMap.keySet().iterator(); while(integerIterator.hasNext()) { System.out.printf(“Integer Value :%dn”, integerIterator.next()); } // iterate values. Iterator<String> stringIterator = stringMap.values().iterator(); while(stringIterator.hasNext()) { System.out.printf(“String Value :%sn”, stringIterator.next()); } } } This will produce the following result − Output Integer Value :10 String Value :Hello World Integer Value :1 Integer Value :2 String Value :Hello World String Value :Hi World Print Page Previous Next Advertisements ”;

Java Generics – Generic Classes

Java Generics – Classes ”; Previous Next A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section. The type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters. Syntax public class Box<T> { private T t; } Where Box − Box is a generic class. T − The generic type parameter passed to generic class. It can take any Object. t − Instance of generic type T. Description The T is a type parameter passed to the generic class Box and should be passed when a Box object is created. 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> 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; } } This will produce the following result. Output Integer Value :10 String Value :Hello World Print Page Previous Next Advertisements ”;

Java Generics – Overview

Java Generics – Overview ”; Previous Next It would be nice if we could write a single sort method that could sort the elements in an Integer array, a String array, or an array of any type that supports ordering. Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time. Using Java Generic concept, we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements. Print Page Previous Next Advertisements ”;

Java Generics – No Instance

Java Generics – No Instance ”; Previous Next A type parameter cannot be used to instantiate its object inside a method. public static <T> void add(Box<T> box) { //compiler error //Cannot instantiate the type T //T item = new T(); //box.add(item); } To achieve such functionality, use reflection. public static <T> void add(Box<T> box, Class<T> clazz) throws InstantiationException, IllegalAccessException{ T item = clazz.newInstance(); // OK box.add(item); System.out.println(“Item added.”); } Example Live Demo package com.tutorialspoint; public class GenericsTester { public static void main(String[] args) throws InstantiationException, IllegalAccessException { Box<String> stringBox = new Box<String>(); add(stringBox, String.class); } public static <T> void add(Box<T> box) { //compiler error //Cannot instantiate the type T //T item = new T(); //box.add(item); } public static <T> void add(Box<T> box, Class<T> clazz) throws InstantiationException, IllegalAccessException{ T item = clazz.newInstance(); // OK box.add(item); System.out.println(“Item added.”); } } class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } } This will produce the following result − Item added. Print Page Previous Next Advertisements ”;

Java Generics – No Array

Java Generics – No Array ”; Previous Next Arrays of parameterized types are not allowed. //Cannot create a generic array of Box<Integer> Box<Integer>[] arrayOfLists = new Box<Integer>[2]; Because compiler uses type erasure, the type parameter is replaced with Object and user can add any type of object to the array. And at runtime, code will not able to throw ArrayStoreException. // compiler error, but if it is allowed Object[] stringBoxes = new Box<String>[]; // OK stringBoxes[0] = new Box<String>(); // An ArrayStoreException should be thrown, //but the runtime can”t detect it. stringBoxes[1] = new Box<Integer>(); Print Page Previous Next Advertisements ”;

Java Generics – No Cast

Java Generics – No Cast ”; Previous Next Casting to a parameterized type is not allowed unless it is parameterized by unbounded wildcards. Box<Integer> integerBox = new Box<Integer>(); Box<Number> numberBox = new Box<Number>(); //Compiler Error: Cannot cast from Box<Number> to Box<Integer> integerBox = (Box<Integer>)numberBox; To achive the same, unbounded wildcards can be used. private static void add(Box<?> box) { Box<Integer> integerBox = (Box<Integer>)box; } Print Page Previous Next Advertisements ”;