排序的數組列表下面的代碼工作:與比較器的Java Lambda表達式
ArrayList<Edge> edges = g.edges();
edges.sort((Comparator.comparingInt(Edge::getWeight)).thenComparing(e -> e.getU() + e.getV() + e.getWeight()));
而做的事情同樣的另一種方式導致編譯時錯誤
ArrayList<Edge> edges = g.edges();
edges.sort(Comparator.comparingInt(f -> f.getWeight()).thenComparing(e -> e.getU() + e.getV() + e.getWeight()));
g.edges()
返回邊緣的一個數組列表。
爲什麼會發生第一種方法,而第二種方法沒有? edges.sort(Comparator.comparingInt(f -> f.getWeight())
就像edges.sort(Comparator.comparingInt(Edge::getWeight))
一樣正常工作,但第一種方法不允許使用.thenComparing(\*lambda exp*\)
,而第二種方法允許使用它。這是爲什麼?
和邊緣類 -
static class Edge {
int u;
int v;
int weight;
int getU() {
return u;
}
int getV() {
return v;
}
int getWeight() {
return weight;
}
Edge(int u, int v, int weight) {
this.u = u;
this.v = v;
this.weight = weight;
}
}
據我所知,這並不算作回答的問題*爲什麼*就是這樣。 – Eugene