”;
Using generics, primitive types can not be passed as type parameters. In the example given below, if we pass int primitive type to box class, then compiler will complain. To mitigate the same, we need to pass the Integer object instead of int primitive type.
Example
package com.tutorialspoint; public class GenericsTester { public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); //compiler errror //ReferenceType //- Syntax error, insert "Dimensions" to complete ReferenceType //Box<int> stringBox = new Box<int>(); integerBox.add(new Integer(10)); printBox(integerBox); } private static void printBox(Box box) { System.out.println("Value: " + box.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
Value: 10
Advertisements
”;