你的代碼:
您已經定義的類型T作爲一個子類的簽名中「媲美」,當你在「T」的數組傳遞給它的參數範圍內使用(T [ ])。編譯器現在知道任何T必須至少是一個Comparable。
更多信息:
總的來說,我不建議直接實現媲美。原因是比較總是在你不知道的背景下。
您應該在Comparable接口上使用Comparator接口來實現與特定上下文的比較。如果你想定義一個自然順序,你可以提供一個自然比較器作爲公共常量。
一些例子:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparatorExample {
public static void main(String[] args) {
List<SomeObject> list = new ArrayList<>();
list.add(new SomeObject(1, "dhjf", "A"));
list.add(new SomeObject(4, "ghdg", "A"));
list.add(new SomeObject(6, "uztzt", "B"));
list.add(new SomeObject(1, "jhgf", "C"));
list.add(new SomeObject(3, "vbbn", "A"));
list.add(new SomeObject(99, "cvcxc", "A"));
list.add(new SomeObject(2, "dfdd", "G"));
// examples
Collections.sort(list, SomeObject.NATURAL);
Collections.sort(list, LexicographicOrderByCategoryAndName.INSTANCE);
LexicographicOrderByName.INSTANCE.compare(new SomeObject(99, "cvcxc", "A"), new SomeObject(54, "fdjnn", "C"));
}
public static class SomeObject {
public static Comparator<SomeObject> NATURAL = new Comparator<SomeObject>() {
@Override
public int compare(SomeObject arg0, SomeObject arg1) {
return arg1.getId() - arg0.getId();
}
};
private int id;
private String name;
private String category;
public SomeObject(int id, String name, String category) {
this.id = id;
this.name = name;
this.category = category;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getCategory() {
return category;
}
}
public static class LexicographicOrderByName implements Comparator<SomeObject> {
public static LexicographicOrderByName INSTANCE = new LexicographicOrderByName();
private LexicographicOrderByName() {
}
@Override
public int compare(SomeObject o1, SomeObject o2) {
return o1.getName().compareTo(o2.getName());
}
}
public static class LexicographicOrderByCategoryAndName implements Comparator<SomeObject> {
public static LexicographicOrderByCategoryAndName INSTANCE = new LexicographicOrderByCategoryAndName();
private LexicographicOrderByCategoryAndName() {
}
@Override
public int compare(SomeObject o1, SomeObject o2) {
int c = o1.getCategory().compareTo(o2.getCategory());
if (c == 0) {
c = o1.getName().compareTo(o2.getName());
}
return c;
}
}
}
與可比接口問題是,一旦你決定一個對象的具體比較,你永遠綁定到它。你可能會改變它,但期望副作用,因爲你不知道所有的上下文是否具有相同的擦除並且應該改變。
它在'anArray'中的對象的類中定義。 –