this problem requires a deep understanding of generics. The principle is clear, but I just don"t understand the problem I"ve explained below
the code is as follows
public class Shape implements Comparable<Shape> {
@Override
public int compareTo(Shape o) {
return 0;
}
}
public class Square extends Shape {
}
public class TestGenetic {
public static <AnyType extends Comparable<? super AnyType>> AnyType findMax(AnyType[] arr){
int maxIndex=0;
for (int i = 0; i <arr.length ; iPP) {
if (arr[i].compareTo(arr[maxIndex+1])>0)
maxIndex=i;
}
return arr[maxIndex];
}
public static void main(String[] args) {
Shape[] shapes={new Shape(),new Shape()};
Square[] squares={new Square(),new Square()};
findMax(shapes);
findMax(squares);
}
}
if you modify generics in generic methods:
public class TestGenetic {
public static <AnyType extends Comparable<AnyType>> AnyType findMax(AnyType[] arr){
int maxIndex=0;
for (int i = 0; i <arr.length ; iPP) {
if (arr[i].compareTo(arr[maxIndex+1])>0)
maxIndex=i;
}
return arr[maxIndex];
}
public static void main(String[] args) {
Shape[] shapes={new Shape(),new Shape()};
Square[] squares={new Square(),new Square()};
findMax(shapes);
findMax(squares);
}
}
will not report an error either
however, this is not the case in generic classes
public class TestGeneric1<AnyType extends Comparable<? super AnyType>> {
public static void main(String[] args) {
TestGeneric1<Square> p=null;
}
}
this won"t report an error, but if I modify the generics, it looks like this:
public class TestGeneric1<AnyType extends Comparable<AnyType>> {
public static void main(String[] args) {
TestGeneric1<Square> p=null;//
}
}
then the compilation error is reported. Why is there a generic check in the generic class, but not in the generic method? in the generic method, Square obviously does not meet the condition of AnyType extends Comparable < AnyType >
.Please give me your advice, thank you