How to create Generic Method in Java

Description

It is possible to create a generic method that is enclosed within a non-generic class.

Example


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;
      }//w  ww. j a  va2  s  .  c o m
    }
    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");
    }
  }
}

The code above generates the following result.

Example 2

The following code declares a copyList() generic method.


/*from  w  w  w  . j  a  va2 s  .co  m*/
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));
  }
}




















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures