Java Generics Tutorial – Generics In Java With Examples

Java Generics Tutorial – Generics in Java tutorial for beginners with examples from Coding compiler. Here you will learn about Java generics and types of generics, generic method, generic interfaces. Learn Now.!

 Java Generics Tutorial

Let’s start learning more about Java generics and other types of generics in Java.

  1. Java generic type
  2. Java generic method
  3. Java generic interface
  4. Java generic class extension
  5. Java generic restrictions

Java Tutorial – What is a generic type in Java

The term generic means a parameterized type. With generics, you can create a single class that works with different types of data. A class, interface, or method that operates on a parameterized type is called generic.

Java Generics Explanation

The following is the syntax for declaring a generic class:

class className<type-param-list> {}

The following is the syntax for declaring a reference to a generic class:

Java Generics Example

Simple generic example

// T is a type parameter that will be replaced by a real type 
// when an object of type Gen is created. 
class Gen<T> {
  T ob; // declare an object of type T
  Gen(T o) {
    ob = o;
  }
  // Return ob.
  T getob() {
    return ob;
  }
  // Show type of T.
  void showType() {
    System.out.println("Type of T is " + ob.getClass().getName());
  }
}

public class Main {
  public static void main(String args[]) {
    Gen<Integer> iOb = new Gen<Integer>(88);
    iOb.showType ();
    int v = iOb.getob();
    System.out.println("value: " + v);
    Gen<String> strOb = new Gen<String>("Generics Test");
    strOb.showType ();
    String str = strOb.getob();
    System.out.println("value: " + str);
  }
}

T is the name of the type parameter. TUsed to declare an object. Generics work only with objects. Generic types vary according to their type parameters.

The above code produces the following results.

Java Generics Example – 2

You can declare multiple type parameters in a generic type.

// A simple generic class with two type parameters: T and V. 
class TwoGen<T, V> {
  T ob1;
  V ob2;
  TwoGen(T o1, V o2) {
    ob1 = o1;
    ob2 = o2;
  }
  void showTypes() {
    System.out.println("Type of T is " + ob1.getClass().getName());
    System.out.println("Type of V is " + ob2.getClass().getName());
  }

  T getob1() {
    return ob1;
  }

  V getob2 () {
    return ob2;
  }
}

public class Main {
  public static void main(String args[]) {
    TwoGen<Integer, String> tgObj = new TwoGen<Integer, String>(88, "Generics");
    tgObj.showTypes();
    int v = tgObj.getob1();
    System.out.println("value: " + v);
    String str = tgObj.getob2();
    System.out.println("value: " + str);
  }
}

Java Generics Example – 3

The following code declares and uses the queue <E> generic type.

class Queue<E> {
  private E[] elements;
  private int head=0, tail=0;

  Queue(int size) {
    elements = (E[]) new Object[size];
  }

  void insert(E element) throws QueueFullException {
    if (isFull())
      throw new QueueFullException();
    elements[tail] = element;
    tail = (tail + 1) % elements.length;
  }

  E remove() throws QueueEmptyException {
    if (isEmpty()){
      throw new QueueEmptyException();
    }
    E element = elements[head];
    head = (head + 1) % elements.length;
    return element;
  }

  boolean isEmpty() {
    return head == tail;
  }

  boolean isFull() {
    return (tail + 1) % elements.length == head;
  }
}
class QueueEmptyException extends Exception {
}

class QueueFullException extends Exception {
}
public class Main{
  public static void main(String[] args) 
      throws QueueFullException, QueueEmptyException {
    Queue<String> queue = new Queue<String>(6);
    System.out.println("Empty: " + queue.isEmpty());
    System.out.println("Full: " + queue.isFull());
    queue.insert("A");
    queue.insert("B");
    queue.insert("C");
    queue.insert("D");
    queue.insert("E");
    System.out.println("Empty: " + queue.isEmpty());
    System.out.println("Full: " + queue.isFull());
    System.out.println("Removing " + queue.remove());
    System.out.println("Empty: " + queue.isEmpty());
    System.out.println("Full: " + queue.isFull());
    System.out.println("Adding F");
    queue.insert("F");
    while (!queue.isEmpty()){
      System.out.println("Removing " + queue.remove());
    }
      
    System.out.println("Empty: " + queue.isEmpty());
    System.out.println("Full: " + queue.isFull());
  }
}

Java Generics – Handling old code

To handle the conversion to generics, Java allows the use of generic class type parameters without any classes.

Below is an example showing the original type:

class MyClass<T> {
  T ob;
  MyClass(T o) {
    ob = o;
  }
  T getob() {
    return ob;
  }
}
public class Main {
  public static void main(String args[]) {
    MyClass raw = new MyClass(new Double(98.6));
    double d = (Double) raw.getob();
    System.out.println("value: " + d);
  }
}

Java Tutorial – How to Create Generic Methods in Java

You can create a generic method that is included in a non-generic class.

public class Main {
  static <T, V extends T> boolean isIn(T x, V[] y) {
    for (int i = 0; i < y.length; i++) {
      if (x.equals(y[i])) {
        return true;
      }
    }
    return false;
  }

  public static void main(String args[]) {
    Integer nums[] = { 1, 2, 3, 4, 5 };
    if (isIn(2, nums)){
      System.out.println("2 is in nums");
    }
    String strs[] = { "one", "two", "three", "four", "five" };
    if (isIn("two", strs)){
      System.out.println("two is in strs");
    }
  }
}

Generic Methods in Jav Example

The following code declares a copy List()generic method.

import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> ls = new ArrayList<String>();
    ls.add("A");
    ls.add("B");
    ls.add("C");
    List<String> lsCopy = new ArrayList<String>();
    copyList (ls, lsCopy);
    List<Integer> lc = new ArrayList<Integer>();
    lc.add(0);
    lc.add(5);
    List<Integer> lcCopy = new ArrayList<Integer>();
    copyList (lc, lcCopy);
  }

  static <T> void copyList(List<T> src, List<T> dest) {
    for (int i = 0; i < src.size(); i++)
      dest.add(src.get(i));
  }
}

Java generic constructor

Constructors can be generic even if their classes are not. For example, consider the following short procedure:

class MyClass {
  private double val;

  <T extends Number> MyClass(T arg) {
    val = arg.doubleValue();
  }

  void showval() {
    System.out.println("val: " + val);
  }
}

public class Main {
  public static void main(String args[]) {
    MyClass test = new MyClass(100);
    MyClass test2 = new MyClass(123.5F);
    test.showval();
    test2.showval();
  }
}

Java Tutorial – How to use the Java Generic Interface

In Java, we create generic interfaces.

Java Generic Interface Explanation

This is a generic syntax for a generic interface:

interface interface-name<type-param-list> { // …

 

Type-param-list is a comma-separated list of type parameters. When implementing a generic interface, you must specify a type parameter as follows:

class class-name<type-param-list>
  implements interface-name<type-arg-list> {

Note

In general, if a class implements a generic interface, the class must also be generic. If a class implements a specific type of generic interface, it looks like this:

class MyClass implements MinMax<Integer> { // OK

 

Then the implementation class does not need to be generic.

Generic interfaces are similar to generic classes.

Example

interface MinMax<T extends Comparable<T>> {
  T max();
}
class MyClass<T extends Comparable<T>> implements MinMax<T> {
  T[] vals;
  MyClass(T[] o) {
    waltz = o;
  }
  public T max() {
    T v = vals[0];
    for (int i = 1; i < vals.length; i++) {
      if (vals[i].compareTo(v) > 0) {
        v = vals[i];
      }
    }
    return v;
  }
}

public class Main {
  public static void main(String args[]) {
    Integer inums[] = { 3, 6, 2, 8, 6 };
    Character chs[] = { "b", "r", "p", "w" };
    MyClass<Integer> a = new MyClass<Integer>(inums);
    MyClass<Character> b = new MyClass<Character>(chs);
    System.out.println(a.max());
    System.out.println(b.max());
  }
}

Java Tutorial – How to extend Java generic classes

 

A generic class can act as a superclass or as a subclass. In a generic hierarchy, any type parameter is required by the generic superclass to be passed up all the subclasses to the hierarchy.

Java generic classes example

Using generic superclasses

class MyClass<T> {
  T ob;
  MyClass(T o) {
    ob = o;
  }
  T getob() {
    return ob;
  }
}
class MySubclass<T, V> extends MyClass<T> {
  V ob2;

  MySubclass(T o, V o2) {
    super (o);
    ob2 = o2;
  }

  V getob2 () {
    return ob2;
  }
}
public class Main {
  public static void main(String args[]) {
    MySubclass<String, Integer> x = new MySubclass<String, Integer>("Value is: ", 99);
    System.out.print(x.getob());
    System.out.println(x.getob2());
  }
}

Java generic classes example – 2

Non-genuine classes are superclasses of generic subclasses that are fully acceptable.

class MyClass {
  int num;

  MyClass(int i) {
    num = i;
  }

  int getnum() {
    return num;
  }
}
class MySubclass<T> extends MyClass {
  T ob;
  MySubclass(T o, int i) {
    super(i);
    ob = o;
  }
  T getob() {
    return ob;
  }
}
public class Main {
  public static void main(String args[]) {
     MySubclass<String> w = new MySubclass<String>("Hello", 4);
    System.out.print(w.getob() + " ");
    System.out.println(w.getnum());
  }
}

Java generic classes example – 3

The instance of an operator can be applied to objects of a generic class.

class Gen<T> {
  T ob;

  Gen (T o) {
    ob = o;
  }
  T getob() {
    return ob;
  }
}
class Gen2<T> extends Gen<T> {
  Gen2(T o) {
    super (o);
  }
}

public class Main {
  public static void main(String args[]) {
    Gen<Integer> iOb = new Gen<Integer>(88);
    Gen2<Integer> iOb2 = new Gen2<Integer>(99);
    Gen2<String> strOb2 = new Gen2<String>("Generics Test");
    System.out.println("iOb2 is instance of Gen2"+(iOb2 instanceof Gen2<?>));
    System.out.println("iOb2 is instance of Gen"+(iOb2 instanceof Gen<?>));
    System.out.println("strOb2 is instance of Gen2"+(strOb2 instanceof Gen2<?>));
    System.out.println("strOb2 is instance of Gen"+(strOb2 instanceof Gen<?>));
    System.out.println("iOb is instance of Gen2"+(iOb instanceof Gen2<?>));
    System.out.println("iOb is instance of Gen"+(iOb instanceof Gen<?>));
  }
}

Java generic classes example – 4

Methods in generic classes can be rewritten just like any other method.

class Gen<T> {
  T obj;
  Gen (T o) {
    obj = o;
  }
  T getob() {
    System.out.print("Gen"s getob(): ");
    return obj;
  }
}
class Gen2<T> extends Gen<T> {
  Gen2(T o) {
    super (o);
  }
  T getob() {
    System.out.print("Gen2"s getob(): ");
    return obj;
  }
}
public class Main {
  public static void main(String args[]) {
    Gen<Integer> iOb = new Gen<Integer>(88);
    Gen2<String> strOb2 = new Gen2<String>("Generics Test");
    System.out.println(iOb.getob());
    System.out.println(strOb2.getob());
  }
}

Java generic type conversion

You can convert one instance of a generic class to another and only two are compatible, and their type parameters are the same.

For example, assuming the following program, this cast is legal:

class Gen<T> {
  T ob;

  Gen (T o) {
    ob = o;
  }
  T getob() {
    return ob;
  }
}
class Gen2<T> extends Gen<T> {
  Gen2(T o) {
    super (o);
  }
}

public class Main {
  public static void main(String args[]) {
    Gen<Integer> iOb = new Gen<Integer>(88);
    Gen2<Integer> iOb2 = new Gen2<Integer>(99);
    Gen2<String> strOb2 = new Gen2<String>("Generics Test");
    iOb = (Gen<Integer>) iOb2;
  }
}

Because iOb2 is an instance of Gen<Integer>. But this actor:

class Gen<T> {
  T ob;

  Gen (T o) {
    ob = o;
  }
  T getob() {
    return ob;
  }
}
class Gen2<T> extends Gen<T> {
  Gen2(T o) {
    super (a);
  }
}

public class Main {
  public static void main(String args[]) {
    Gen<Integer> iOb = new Gen<Integer>(88);
    Gen2<Integer> iOb2 = new Gen2<Integer>(99);
    Gen2<String> strOb2 = new Gen2<String>("Generics Test");
    //iOb = (Gen<Long>) iOb2;//wrong
  }
}

It is illegal because iOb2 is not an instance of Gen<Long>.

Java Tutorial – What are Java generic restrictions

Let’s here we will discuss on Java generic restrictions.

Type parameters cannot be instantiated

You cannot create an instance of a type parameter. For example, consider this class:

// Can"t create an instance of T. 
 class Gen<T> {
  T ob;

  Gen() {
    Ob = new T(); // Illegal!!!
   }
}

Static member restrictions

No static member can use the type parameter declared by the wrapper class. For example, all static members of this class are illegal:

Class Wrong<T> {
   // Wrong, no static variables of type T.
  static T ob;

  // Wrong, no static method can use T.
  static T getob() {
     return ob;
  }

  // Wrong, no static method can access object of type T.
  static void show ob() {
    System.out.println(ob);
  }
}

You can declare static generic methods with your own type parameters.

Generic array limit

You cannot instantiate an array whose base type is a type parameter. You cannot create an array of type-specific generic references.

The following short program shows two cases:

Class MyClass<T extends Number> {
  T ob;
  T vals[];

  MyClass(T o, T[] nums) {
    Ob = o;
    Vals = nums;
  }
}

Public class Main {
   public static void main(String args[]) {
     Integer n[] = { 1 };
    MyClass< Integer > iOb = new MyClass< Integer >(50, n);
     // Can"t create an array of type-specific generic references.
    // Gen<Integer> gens[] = new Gen<Integer>[10] ; 
     MyClass<?> gens[] = new MyClass<?>[10]; // OK
   }
}

Related Java Tutorials & Interview Questions

Related Java Tutorials & Interview Questions
Introduction to Java Programming Java Annotations Tutorial For Beginners
Java Keywords Tutorial For Beginners Core Java Multiple Choice Questions
Java Data Types Tutorial For Beginners 21 Aricent Java Interview Questions
Java Operators Tutorial For Beginners 53 Accenture Java Interview Questions
Java Control Flow Statements Tutorial 399 Core Java Interview Questions
Java Performance Tuning Tips 581 Advanced Java Interview Questions
Java Class Tutorial For Beginners 60 Java Multiple Choice Questions And Answers
Java Exceptions Tutorial For Beginners More Java Interview Questions..

Leave a Comment