泛型,就是定义类或方法的时候,没有指定类型。使用的时候可以使用任何类型,这就是泛型的优势。
列子1:
public class Point<T> {
private T x;
private T y;
public T getX() {
return x;
}
public void setX(T x) {
this.x = x;
}
public T getY() {
return y;
}
public void setY(T y) {
this.y = y;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
public
static
void
main(String[] args) {
Point<Integer> p=new Point<Integer>();
p.setX(12);
p.setY(11);
System.out.println(p.toString());
Point<String> p1=new Point<String>();
p1.setX("gao");
p1.setY("ying");
System.out.println(p1.toString());
}
}
例子2:
public class MyMap<K,V> {
private K key;
private V value;
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public void put(K key,V value){
this.key=key;
this.value=value;
}
@Override
public String toString() {
return "MyMap [key=" + key + ", value=" + value + "]";
}
//测试
public static void main(String[] args) {
MyMap<Integer,String> mp=new MyMap<Integer,String>();
mp.put(1, "aa");
System.out.println(mp.toString());
}
}
泛型方法
public class myArray {
public static void main(String[] args) {
//Test(1,2,4);
//Test2("aa",2,"cc",true);
Test3(2,4,5,"a",true);
}
public static void Test(int ...i) {
for (int j = 0; j < i.length; j++) {
System.out.print(i[j]+" ");
}
}
@SafeVarargs
public static <T> void Test2(T ...i) {
for (int j = 0; j < i.length; j++) {
System.out.print(i[j]+" ");
}
}
public static void Test3(Object...i) {
for (int j = 0; j < i.length; j++) {
System.out.print(i[j]+" ");
}
}
}