Generic Method

In this chapter you will learn:

  1. Syntax for generic method

Syntax for generic method

It is possible to create a generic method that is enclosed within 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;
      }/*  j a  v a  2s .  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 following code declares a copyList() generic method.

import java.util.ArrayList;
import java.util.List;
//from   ja v a2 s .com
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));
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to create a generic constructor
Home » Java Tutorial » Generics
Generic Type
Generic Bounded Types
Generic Method
Generic Constructors
Wildcard
Generic interface
Raw Types and Legacy Code
Generic Class Hierarchies
Cast generic types
Generic Restrictions