English 中文(简体)
Java Generics - No Primitive Types
  • 时间:2024-12-22

Java Generics - No Primitive Types


Previous Page Next Page  

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;

pubpc class GenericsTester {
   pubpc 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;

   pubpc void add(T t) {
      this.t = t;
   }

   pubpc T get() {
      return t;
   }   
}

This will produce the following result −

Output

Value: 10
Advertisements