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 ”;
Category: java Generics
Java Generics – Multiple Bounds ”; Previous Next A type parameter can have multiple bounds. Syntax public static <T extends Number & Comparable<T>> T maximum(T x, T y, T z) Where maximum − maximum is a generic method. T − The generic type parameter passed to generic method. It can take any Object. Description The T is a type parameter passed to the generic class Box and should be subtype of Number class and must implments Comparable interface. In case a class is passed as bound, it should be passed first before interface otherwise compile time error will occur. Example Create the following java program using any editor of your choice. Live Demo package com.tutorialspoint; public class GenericsTester { 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 )); } public static <T extends Number & Comparable<T>> T maximum(T x, T y, T z) { T max = x; if(y.compareTo(max) > 0) { max = y; } if(z.compareTo(max) > 0) { max = z; } return max; } // Compiler throws error in case of below declaration /* public static <T extends Comparable<T> & Number> T maximum1(T x, T y, T z) { T max = x; if(y.compareTo(max) > 0) { max = y; } if(z.compareTo(max) > 0) { max = z; } return max; }*/ } 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 Print Page Previous Next Advertisements ”;
Java Generics – Raw Types
Java Generics – Raw Types ”; Previous Next A raw type is an object of a generic class or interface if its type arguments are not passed during its creation. 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> box = new Box<Integer>(); box.set(Integer.valueOf(10)); System.out.printf(“Integer Value :%dn”, box.getData()); Box rawBox = new Box(); //No warning rawBox = box; System.out.printf(“Integer Value :%dn”, rawBox.getData()); //Warning for unchecked invocation to set(T) rawBox.set(Integer.valueOf(10)); System.out.printf(“Integer Value :%dn”, rawBox.getData()); //Warning for unchecked conversion box = rawBox; System.out.printf(“Integer Value :%dn”, box.getData()); } } class Box<T> { private T t; public void set(T t) { this.t = t; } public T getData() { return t; } } This will produce the following result. Output Integer Value :10 Integer Value :10 Integer Value :10 Integer Value :10 Print Page Previous Next Advertisements ”;
Java Generics – Generic Set
Java Generics – Set ”; Previous Next Java has provided generic support in Set 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.HashSet; import java.util.Iterator; import java.util.Set; public class GenericsTester { public static void main(String[] args) { Set<Integer> integerSet = new HashSet<Integer>(); integerSet.add(Integer.valueOf(10)); integerSet.add(Integer.valueOf(11)); Set<String> stringSet = new HashSet<String>(); stringSet.add(“Hello World”); stringSet.add(“Hi World”); for(Integer data: integerSet) { System.out.printf(“Integer Value :%dn”, data); } Iterator<String> stringIterator = stringSet.iterator(); while(stringIterator.hasNext()) { System.out.printf(“String Value :%sn”, stringIterator.next()); } } } This will produce the following result − Output Integer Value :10 Integer Value :11 String Value :Hello World String Value :Hi World Print Page Previous Next Advertisements ”;
Java Generics – Generic List
Java Generics – List ”; Previous Next Java has provided generic support in List interface. Syntax List<T> list = new ArrayList<T>(); Where list − object of List interface. T − The generic type parameter passed during list declaration. Description The T is a type parameter passed to the generic interface List and its implemenation class ArrayList. Example Create the following java program using any editor of your choice. Live Demo package com.tutorialspoint; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class GenericsTester { public static void main(String[] args) { List<Integer> integerList = new ArrayList<Integer>(); integerList.add(Integer.valueOf(10)); integerList.add(Integer.valueOf(11)); List<String> stringList = new ArrayList<String>(); stringList.add(“Hello World”); stringList.add(“Hi World”); System.out.printf(“Integer Value :%dn”, integerList.get(0)); System.out.printf(“String Value :%sn”, stringList.get(0)); for(Integer data: integerList) { System.out.printf(“Integer Value :%dn”, data); } Iterator<String> stringIterator = stringList.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 :10 Integer Value :11 String Value :Hello World String Value :Hi World Print Page Previous Next Advertisements ”;
Type Parameter Naming Conventions ”; Previous Next By convention, type parameter names are named as single, uppercase letters so that a type parameter can be distinguished easily with an ordinary class or interface name. Following is the list of commonly used type parameter names − E − Element, and is mainly used by Java Collections framework. K − Key, and is mainly used to represent parameter type of key of a map. V − Value, and is mainly used to represent parameter type of value of a map. N − Number, and is mainly used to represent numbers. T − Type, and is mainly used to represent first generic type parameter. S − Type, and is mainly used to represent second generic type parameter. U − Type, and is mainly used to represent third generic type parameter. V − Type, and is mainly used to represent fourth generic type parameter. 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; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; 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()); Pair<String, Integer> pair = new Pair<String, Integer>(); pair.addKeyValue(“1”, Integer.valueOf(10)); System.out.printf(“(Pair)Integer Value :%dn”, pair.getValue(“1”)); CustomList<Box> list = new CustomList<Box>(); list.addItem(box); System.out.printf(“(CustomList)Integer Value :%dn”, list.getItem(0).getFirst()); } } 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; } } class Pair<K,V>{ private Map<K,V> map = new HashMap<K,V>(); public void addKeyValue(K key, V value) { map.put(key, value); } public V getValue(K key) { return map.get(key); } } class CustomList<E>{ private List<E> list = new ArrayList<E>(); public void addItem(E value) { list.add(value); } public E getItem(int index) { return list.get(index); } } This will produce the following result. Output Integer Value :10 String Value :Hello World (Pair)Integer Value :10 (CustomList)Integer Value :10 Print Page Previous Next Advertisements ”;
Java Generics – Type Inference ”; Previous Next Type inference represents the Java compiler”s ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned. Inference algorithms tries to find a specific type which can fullfill all type parameters. Compiler generates unchecked conversion warning in-case type inference is not used. Syntax Box<Integer> integerBox = new Box<>(); Where Box − Box is a generic class. <> − The diamond operator denotes type inference. Description Using diamond operator, compiler determines the type of the parameter. This operator is avalilable from Java SE 7 version onwards. 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) { //type inference Box<Integer> integerBox = new Box<>(); //unchecked conversion warning 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 – Parameterized Types ”; Previous Next A Generic class can have parameterized types where a type parameter can be substituted with a parameterized type. 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; import java.util.ArrayList; import java.util.List; public class GenericsTester { public static void main(String[] args) { Box<Integer, List<String>> box = new Box<Integer, List<String>>(); List<String> messages = new ArrayList<String>(); messages.add(“Hi”); messages.add(“Hello”); messages.add(“Bye”); box.add(Integer.valueOf(10),messages); System.out.printf(“Integer Value :%dn”, box.getFirst()); System.out.printf(“String Value :%sn”, box.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 :[Hi, Hello, Bye] Print Page Previous Next Advertisements ”;
Java Generics – Discussion
Discuss Java Generics ”; Previous Next 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. This reference will take you through simple and practical methods using Java Generics. Print Page Previous Next Advertisements ”;
Java Generics – Quick Guide
Java Generics – Quick Guide ”; Previous Next Java Generics – Overview 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. Java Generics – Environment Setup Local Environment Setup JUnit is a framework for Java, so the very first requirement is to have JDK installed in your machine. System Requirement JDK 1.5 or above. Memory No minimum requirement. Disk Space No minimum requirement. Operating System No minimum requirement. Step 1: Verify Java Installation in Your Machine First of all, open the console and execute a java command based on the operating system you are working on. OS Task Command Windows Open Command Console c:> java -version Linux Open Command Terminal $ java -version Mac Open Terminal machine:< joseph$ java -version Let”s verify the output for all the operating systems − OS Output Windows java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing) Linux java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing) Mac java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing) If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link https://www.oracle.com. We are assuming Java 1.6.0_21 as the installed version for this tutorial. Step 2: Set JAVA Environment Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example. OS Output Windows Set the environment variable JAVA_HOME to C:Program FilesJavajdk1.6.0_21 Linux export JAVA_HOME = /usr/local/java-current Mac export JAVA_HOME = /Library/Java/Home Append Java compiler location to the System Path. OS Output Windows Append the string C:Program FilesJavajdk1.6.0_21bin at the end of the system variable, Path. Linux export PATH = $PATH:$JAVA_HOME/bin/ Mac not required Verify Java installation using the command java -version as explained above. Java Generics – Classes 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 Type Parameter Naming Conventions By convention, type parameter names are named as single, uppercase letters so that a type parameter can be distinguished easily with an ordinary class or interface name. Following is the list of commonly used type parameter names − E − Element, and is mainly used by Java Collections framework. K − Key, and is mainly used to represent parameter type of key of a map. V − Value, and is mainly used to represent parameter type of value of a map. N − Number, and is mainly used to represent numbers. T − Type, and is mainly used to represent first generic type parameter. S − Type, and is mainly used to represent second generic type parameter. U − Type, and is mainly used to represent third generic type parameter. V − Type, and is mainly used to represent fourth generic type parameter. 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; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; 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()); Pair<String, Integer> pair = new Pair<String, Integer>(); pair.addKeyValue(“1”, Integer.valueOf(10)); System.out.printf(“(Pair)Integer Value :%dn”, pair.getValue(“1”)); CustomList<Box> list = new CustomList<Box>(); list.addItem(box); System.out.printf(“(CustomList)Integer Value :%dn”, list.getItem(0).getFirst()); } } 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; } } class Pair<K,V>{ private Map<K,V> map = new HashMap<K,V>(); public void addKeyValue(K key, V value) { map.put(key, value); } public V getValue(K key) { return map.get(key); } } class CustomList<E>{ private List<E> list = new ArrayList<E>(); public void addItem(E value) { list.add(value); } public E getItem(int index) { return list.get(index); } } This will produce the following result. Output Integer Value :10 String Value :Hello World (Pair)Integer Value :10 (CustomList)Integer Value :10 Java Generics – Type Inference Type inference represents the Java compiler”s ability to look at a method invocation and its corresponding