相关疑难解决方法(0)

Java Integer compareTo() - 为什么使用比较与减法?

我发现方法的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)

java optimization comparison integer overflow

78
推荐指数
3
解决办法
1万
查看次数

按属性值对对象列表进行排序

我有一份城市名单.

 List<City> cities;
Run Code Online (Sandbox Code Playgroud)

我想按人口排序.我想象的代码是这样的:

 cities.Sort(x => x.population);
Run Code Online (Sandbox Code Playgroud)

但这不起作用.我应该如何排序这个清单?

c#

23
推荐指数
3
解决办法
6万
查看次数

标签 统计

c# ×1

comparison ×1

integer ×1

java ×1

optimization ×1

overflow ×1