泛型
作用:为了保证数据类型的安全性。
示例:
public class Point < T > {
private T x;
private T y;
public Point ( ) { }
public Point ( T x, T y) {
this . x = x;
this . y = y;
}
}
public class Location < E , T > {
private E x;
private T y;
public Location ( ) { }
public Location ( E x, T y) {
this . x = x;
this . y = y;
}
}
泛型的菱形语法
Point < String > p3 = new Point < > ( ) ;
Point < Float > p5 = new Point < > ( 67.4f , 48.3f ) ;
Location < Float , Integer > lo1 = new Location < > ( ) ;
一、定义泛型接口与类
public class Point < T > { }
public class ArrayList < E > { }
public interface A < E > { }
public interface B < E , T > { }
public interface List < E > { }
public interface Map < K , V > { }
二、类型通配符
public static void test ( Point < ? > p) {
}
public static void main ( String [ ] args) {
Point < String > p1 = new Point < > ( ) ;
test ( p1) ;
Point < Float > p2 = new Point < > ( ) ;
test ( p2) ;
}
三、设置类型通配符的上限
public static void test ( Point < ? extends Account > p) {
}
public static void main ( String [ ] args) {
Point < SavingAccount > p1 = new Point < > ( ) ;
Point < CreditAccount > p2 = new Point < > ( ) ;
test ( p1) ;
test ( p2) ;
}
四、设置泛型的上限
public class Point < T extends Number > {
}
五、泛型方法
public class Point {
public static < E > void test ( Point < E > p) {
}
}
六、泛型与通配符
public void test ( Point < ? extends E > ) {
}
}
Point < Account > p = new Point < > ( ) ;
test ( p) ;
public boolean addAll ( Collection < ? extends E > c) { }
七、通配符的下限
public class Point < E > {
public void test ( Point < ? super E > ) {
}
}