Generics in Java code example

Example 1: java generic type method

// generic methods

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

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

// bounded generics

public <T extends Number> List<T> fromArrayToList(T[] a) {
	    ...
	}

//multiple bounds

<T extends Number & Comparable>

// upper bound wildcards

public static void paintAllBuildings(List<? extends Building> buildings) {
	    ...
	}
    
// lower bound wildcard

<? super T>

Example 2: 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));
  }
}

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:

EElement (used extensively by the Java Collections Framework, for example ArrayList, Set etc.)
KKey (Used in Map)
NNumber
TType
VValue (Used in Map)
S,U,V etc.2nd, 3rd, 4th types

Example 5: generics Interface in java

/*Suppose we want to restrict the type of objects that can be used in the parameterized type, for example in a method that compares two objects and we want to make sure that the accepted objects are Comparables. To declare a bounded type parameter, list the type parameter’s name, followed by the extends keyword, followed by its upper bound, similar like below method.

The invocation of these methods is similar to unbounded method except that if we will try to use any class that is not Comparable, it will throw compile-time error.

Bounded type parameters can be used with methods as well as classes and interfaces.

Java Generics supports multiple bounds also, i.e <T extends A & B & C>. In this case, A can be an interface or class. If A is class then B and C should be an interface. We can’t have more than one class in multiple bounds.*/
public static <T extends Comparable<T>> int compare(T t1, T t2){
		return t1.compareTo(t2);
	}

Example 6: generics Interface in java

/*We know that Java inheritance allows us to assign a variable A to another variable B if A is subclass of B. So we might think that any generic type of A can be assigned to generic type of B, but it’s not the case. Let’s see this with a simple program.

We are not allowed to assign MyClass<String> variable to MyClass<Object> variable because they are not related, in fact MyClass<T> parent is Object.*/
package com.journaldev.generics;

public class GenericsInheritance {

	public static void main(String[] args) {
		String str = "abc";
		Object obj = new Object();
		obj=str; // works because String is-a Object, inheritance in java
		
		MyClass<String> myClass1 = new MyClass<String>();
		MyClass<Object> myClass2 = new MyClass<Object>();
		//myClass2=myClass1; // compilation error since MyClass<String> is not a MyClass<Object>
		obj = myClass1; // MyClass<T> parent is Object
	}
	
	public static class MyClass<T>{}

}

Tags:

Java Example