小弟初次尝试java泛型遭遇困境无法解决,求大神前辈指点迷境,不胜感谢
public class Max <DataType extends Comparable < DataType > > {
public static DataType max(DataType a, DataType b) {
int cmp = a.compareTo(b);
if (cmp == -1) {
return b;
}
return a;
}
}
Eclipse爆出编译错误如下:
Multiple markers at this line
- Cannot make a static reference to the non-static type
DataType
- Cannot make a static reference to the non-static type
DataType
- Cannot make a static reference to the non-static type
DataType
------解决方案--------------------
泛型放在方法上
public class Max {
public static <T extends Comparable < T >> T max(T a, T b) {
int cmp = a.compareTo(b);
if (cmp == -1) {
return b;
}
return a;
}
}
------解决方案--------------------
使用方法泛型可以满足你的要求。
代码大致是:
public class Max {
public static <DataType extends Comparable<DataType>> DataType max(DataType a, DataType b) {
int cmp = a.compareTo(b);
if (cmp == -1) {
return b;
}
return a;
}
}