generics java code example

Example 1: java generic type method

// generic methods

public  List fromArrayToList(T[] a) {   
	    return Arrays.stream(a).collect(Collectors.toList());
	}

public static  List fromArrayToList(T[] a, Function mapperFunction) {
	    return Arrays.stream(a)
	      .map(mapperFunction)
	      .collect(Collectors.toList());
	}

// bounded generics

public  List fromArrayToList(T[] a) {
	    ...
	}

//multiple bounds



// upper bound wildcards

public static void paintAllBuildings(List buildings) {
	    ...
	}
    
// lower bound wildcard

Example 2: java generics

public class Tuple  {
  // 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  intTuple = new Tuple (5, 500)
    Tuple  stringTuple = new Tuple  ("Hello", "World")

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

Example 3: generic argument java

static void fromArrayToCollection(Object[] a, Collection c) {
    for (Object o : a) { 
        c.add(o); // compile-time error
    }
}

Example 4: java generics type

Java Generic Type Naming convention helps us understanding code easily and having a naming convention is one of the best practices of Java programming language. So generics also comes with its own naming conventions. Usually, type parameter names are single, uppercase letters to make it easily distinguishable from java variables. The most commonly used type parameter names are:

E – Element (used extensively by the Java Collections Framework, for example ArrayList, Set etc.)
K – Key (Used in Map)
N – Number
T – Type
V – Value (Used in Map)
S,U,V etc. – 2nd, 3rd, 4th types

Tags:

Misc Example