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;
}
}
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;
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 Book
Language Basics
Java Book
Language Basics
Generics:
- Generic Class
- Generic Bounded Types
- Generic Wildcard Arguments
- Generic Bounded Wildcards
- Generic Method
- Generic Constructors
- Generic Interfaces
- Raw Types and Legacy Code
- Generic Class Hierarchies
- Run-Time Type Comparisons Within a Generic Hierarchy
- Overriding Methods in a Generic Class
- Generic Restrictions
- Generic Array Restrictions