Java - Use of generic type

By xngo on June 23, 2019

package net.xngo.tutorial.java.lang;
 
/**
 * Show use of generic type.
 * http://docs.oracle.com/javase/tutorial/java/generics/types.html
 * http://www.oracle.com/technetwork/articles/java/juneau-generics-2255374.html
 * @author Xuan Ngo
 *
 */
public class GenericType
{
  /**
   * Generic version of the Box class.
   * @param <T> the type of the value being boxed
   */
  public class Box<T> 
  {
      // T stands for "Type"
      private T t;
 
      public void set(T t) { this.t = t; }
      public T get() { return t; }
  }  
 
  public static void main(String[] args)
  {
    GenericType gt = new GenericType();
 
    Box<Integer> integerBox = gt.new Box<Integer>();
    integerBox.set(new Integer(2));
    System.out.println(integerBox.get());
 
    Box<String> stringBox = gt.new Box<String>();
    stringBox.set(new String("String"));
    System.out.println(stringBox.get());    
 
  }
 
}

https://github.com/xuanngo/Tutorial/blob/master/src/net/xngo/tutorial/java/lang/GenericType.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.