我有以下代码
public class Mamman14 {
public static void main(String[] args) {
// TODO code application logic here
}
public class SortedPair < E extends Comparable < E >> {
E Max_Element;
E Min_Element;
public SortedPair(E FirstElement, E SecondElemnt) throws IllegalPair {
int Compare_Result = FirstElement.compareTo(SecondElemnt);
if (Compare_Result == 0) {
Max_Element = null;
Min_Element = null;
throw new IllegalPair(FirstElement.toString(), SecondElemnt.toString());
} else if (Compare_Result > 0) {
Max_Element = FirstElement;
Min_Element = SecondElemnt;
} else {
Max_Element = SecondElemnt;
Min_Element = FirstElement;
}
}
public E getFirst() {
return Max_Element;
}
public E getSecond() {
return Min_Element;
}
@
Override
public String toString() {
return String.format("%s is bigger then %s.", getFirst(), getSecond());
}
}
public class IllegalPair extends Exception {
public IllegalPair() {
super("Elements must be different!!");
}
public IllegalPair(String Element) {
super("Elements must be different!! \n However they are equal to " + Element);
}
public IllegalPair(String Element1, String Element2) {
super("Elements must be different!! \n However the elements are " + Element1 + "and" +
Element2 + "and they are equal.");
}
}
}
这是一个简单的程序,它比较两个元素并相应地将它们设置在 Max_Element 和 Min_Element 中。我有两个问题:
当我写public class SortedPair <E extends Comparable<E>>
这是否意味着 SortedPair 只能接收包含 compareTo 方法的可比较元素?
在throw new IllegalPair(FirstElement.toString(), SecondElemnt.toString())
我使用元素的 toString() 方法创建一个新对象的行中,假设元素没有 toString() 方法,发送的是什么?
谢谢。