我发现方法的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) 免责声明:我已经发布过一次这样的问题,并且被标记为重复。请尝试帮助我。我已经浏览了 stackoverflow 上以前的所有方法,但没有任何帮助。所有提到的对 Map(Key,Values) 进行排序的方法在我的情况下都不起作用,因为我还需要更进一步,即检索值的属性。这一次,我尝试提供完整的细节。
我有一个 Java 中的映射(字符串,对象),我想使用对象的属性之一对其进行排序。
例如假设我有一堂课
class Entry
{
int id;
String name;
String address;
//Rest of the code
}
Run Code Online (Sandbox Code Playgroud)
现在,我创建了一张地图
Map<String,Entry>
Run Code Online (Sandbox Code Playgroud)
我想按类 Entry 的属性 id (Entry.id) 对地图进行排序
请帮忙 !
例如,我有三个 Entry 类的对象
entry1 :
id=1
name="abc"
address="india"
entry2 :
id=2
name="xyz"
address="india"
entry3 :
id=3
name="pqr"
address="india"
Run Code Online (Sandbox Code Playgroud)
现在,我的地图最初如下:
Key : Value
first: entry2
second: entry3
third : entry1
Run Code Online (Sandbox Code Playgroud)
排序后应该是这样的
Key : Value
third : entry1
first: entry2
second: entry3
Run Code Online (Sandbox Code Playgroud)