我发现方法的java.lang.Integer实现compareTo如下:
public int compareTo(Integer anotherInteger) {
int thisVal = this.value;
int anotherVal = anotherInteger.value;
return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
}
Run Code Online (Sandbox Code Playgroud)
问题是为什么使用比较而不是减法:
return thisVal - anotherVal;
Run Code Online (Sandbox Code Playgroud) 我有一份城市名单.
List<City> cities;
Run Code Online (Sandbox Code Playgroud)
我想按人口排序.我想象的代码是这样的:
cities.Sort(x => x.population);
Run Code Online (Sandbox Code Playgroud)
但这不起作用.我应该如何排序这个清单?