java 代码精简之利用泛型
3.1.泛型接口
在 Java 没有引入泛型前,都是采用 Object 表示通用对象,最大的问题就是类型无法强校验并且需要强制类型转换。
普通:
public interface Comparable {
public int compareTo(Object other);
}
@Getter
@Setter
@ToString
public class UserVO implements Comparable {
private Long id;
@Override
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);
}
@Getter
@Setter
@ToString
public class UserVO implements Comparable<UserVO> {
private Long id;
@Override
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.泛型方法
普通:
public static Map<String, Integer> newHashMap(String[] keys, Integer[] values) {
// 检查参数非空
if (ArrayUtils.isEmpty(keys) || ArrayUtils.isEmpty(values)) {
return Collections.emptyMap();
}
// 转化哈希映射
Map<String, Integer> map = new HashMap<>();
int length = Math.min(keys.length, values.length);
for (int i = 0; i < length; i++) {
map.put(keys[i], values[i]);
}
return map;
}
...
精简:
public static <K, V> Map<K, V> newHashMap(K[] keys, V[] values) {
// 检查参数非空
if (ArrayUtils.isEmpty(keys) || ArrayUtils.isEmpty(values)) {
return Collections.emptyMap();
}
// 转化哈希映射
Map<K, V> map = new HashMap<>();
int length = Math.min(keys.length, values.length);
for (int i = 0; i < length; i++) {
map.put(keys[i], values[i]);
}
return map;
}
...
以上内容就是关于IT教育的更多相关介绍,如果还有不懂的地方欢迎您登陆到西安鸥鹏教育网站http://www.xianoupeng.com/了解详情。