Fork me on GitHub

泛型

利用对象的多态性,可以解决方法参数统一的问题,但是随之而来的就是另外一个问题:并不是所有的向下转型都是安全的。从JDK 1.5开始提供了泛型技术,可以有效的解决这一问题

泛型类

如果要开发一套地理信息系统,必定存在描述精度和纬度的数据,可以有三种数据类型:

  • 整型
  • 浮点型
  • 字符串

相应的,如果要统一参数类型,就会存在三种转型关系:

  • int型自动封装成Integer,向上转型为Object,Object向下转型为Integer,Integer拆封成int
  • double->Double>Objec, Object->Double->double-
  • String->Object,Object->String

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Point<T>{
private T x;
private T y;
public void setX(T x) {
this.x=x;
}
public void setY(T y) {
this.y=y;
}
public T getX() {
return x;
}
public T getY() {
return y;
}
}
public class testDemo7 {
public static void main(String args[]) {

//引用类型是字符型
Point<String> p=new Point<>();
p.setX("东经 120");
p.setY("北纬 50");
String x=p.getX(); //自动拆箱
String y=p.getY(); //自动拆箱
System.out.println("经度:"+x+",维度:"+y);
//引用类型是整型
Point<Integer> p1=new Point<>();
p1.setX(120);
p1.setY(50);
int x1=p1.getX(); //自动拆箱
int y1=p1.getY(); //自动拆箱
System.out.println("经度:"+x1+",维度:"+y1);
//引用类型是浮点型
Point<Double> p2=new Point<>();
p2.setX(120.5);
p2.setY(50.0);
double x2=p2.getX(); //自动拆箱
double y2=p2.getY(); //自动拆箱
System.out.println("经度:"+x2+",维度:"+y2);
}
}

使用泛型后,类中的属性都是动态设置的,从而避免了向下转型的不安全性。
能够采用泛型的只能够是引用类型,不能是基本类型

泛型接口

除了类可以设置泛型,接口也可以设置泛型

在子类继续设置泛型标记,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
interface Message<T>{
public void print(T t);
}
class SonMessage<S> implements Message<S>{
public void print(S t) {
System.out.println(t);
}
}
public class testDemo7{
public static void main(String args[]) {
Message<String> m=new SonMessage<>();
m.print("hello");
}

}

也可以在子类中不设置泛型,可以明确定义一个泛型类型,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
interface Message<T>{
public void print(T t);
}
class SonMessage implements Message<String>{
public void print(String t) {
System.out.println(t);
}
}
public class testDemo7{
public static void main(String args[]) {
Message<String> m=new SonMessage();
m.print("helloWorld");
}

}

泛型方法

代码如下:

1
2
3
4
5
6
7
8
9
public class testDemo7{
public static void main(String args[]) {
String str=fun("hello world");
System.out.println(str.length());
}
public static <T> T fun(T t) {
return t;
}
}
-------------本文结束感谢您的阅读-------------
Donate comment here