我是Java新手,特别是抽象类和接口语法。
我有以下代码:
public class JavaTestsHomework1 {
public interface Comparable{
public int compareTo();
}
abstract class Int implements Comparable{
private int x;
public Int(int x) {
this.x = x;
}
public int compareTo(Int other) {
return x - other.x;
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
}
}
我的问题是:如何以Comparable
方法返回compareTo()
的结果的方式实现接口x - other.x
?
我是否需要在main()
的某处调用某个方法?
对于初学者来说,深入,易于理解的解释会很棒。我已经在互联网上搜索答案,但没有运气......至少我无法理解。
答案 0 :(得分:0)
如果要使自定义类具有可比性,则应使用Java库中已存在的类,即java.lang.Comparable
。重新实现具有相同名称的Java类不是一个好主意,它是错误和混淆的来源。
相反,您应该使用已经存在的那个:
import java.lang.Comparable;
abstract class Int implements Comparable<Int> {
private int x;
public Int(int x) {
this.x = x;
}
@Override
public int compareTo(Int other) {
return x - other.x;
}
@Override
public String toString() {
return Integer.toString(x);
}
}
然后你可以明确地使用它
public static void main(String[] args) {
Int i1 = new Int(2){}; // creation of anonymous class with empty class declaration body
Int i2 = new Int(5){};
System.out.println(i1.compareTo(i2)); // returns -3
}
当您创建某种集合时,Java会在窗帘后面使用它:
public static void main(String[] args) {
java.util.List<Int> ints = new java.util.ArrayList<>();
ints.add(new Int(3){});
ints.add(new Int(1){});
ints.add(new Int(2){});
java.util.Collections.sort(ints); // Uses compareTo
System.out.println(ints); // Will print [1, 2, 3]
}