3.1. 泛型接口
在 Java 没有引入泛型前,都是采用 Object 表示通用对象,最大的问题就是类型无法强校验并且需要强制类型转换。
普通:
public interface Comparable {
public int compareTo(Object other);
}
public class UserVO implements Comparable {
private Long id;
public int compareTo(Object other) {
UserVO user = (UserVO)other;
return Long.compare(this.id, user.id);
}
}
精简:
public interface Comparable<T> {
public int compareTo(T other);
}
public class UserVO implements Comparable<UserVO> {
private Long id;
public int compareTo(UserVO other) {
return Long.compare(this.id, other.id);
}
}
3.2. 泛型类
普通:
@Getter
@Setter
@ToString
public class IntPoint {
private Integer x;
private Integer y;
}
@Getter
@Setter
@ToString
public class DoublePoint {
private Double x;
private Double y;
}
精简:
@Getter
@Setter
@ToString
public class Point<T extends Number> {
private T x;
private T y;
}
3.3. 泛型方法
普通:
< , > ( [] keys, [] values) {
// 检查参数非空
if (. (keys) || . (values)) {
return . ();
}
// 转化哈希映射
< , > map = new <>();
int length = . (keys.length, values.length);
for (int = 0; < length; ++) {
map. (keys[ ], values[ ]);
}
return map;
}
精简:
< , > < , > ( [] keys, [] values) {
// 检查参数非空
if (. (keys) || . (values)) {
return . ();
}
// 转化哈希映射
< , > map = new <>();
int length = . (keys.length, values.length);
for (int = 0; < length; ++) {
map. (keys[ ], values[ ]);
}
return map;
}
正文完