? java generics code example

Example: java generics

public class Tuple <T> {
  // the T is a placeholder for any datatype
  public T leftValue;
  public T rightValue;
  
  public Tuple(T leftValue, T rightValue){
    // again, T is being used as a placeholder for any type
    this.leftValue = leftValue;
    this.rightValue = rightValue;
}

public class Program{
  public static void main (String args){
    // And upon using Tuples we can fill in the T from the Tuple class with actual datatypes
    Tuple <int> intTuple = new Tuple <int>(5, 500)
    Tuple <String> stringTuple = new Tuple <String> ("Hello", "World")

    // we can even put Tuples inside of Tuples!
    Tuple<Tuple<int>> metaIntTuple = new Tuple <Tuple <int>> (intTuple, new Tuple <int> (456, 0));
  }
}

Tags: