gpt4 book ai didi

java - 重写 ArrayList 类 - Java

转载 作者:行者123 更新时间:2023-12-01 23:52:05 25 4
gpt4 key购买 nike

我正在准备期末考试,我正在看期中考试中的一个问题,我错了,老实说我不确定如何去做。问题如下:

Rewrite the Person class so that if you have an ArrayList of Person objects, ArrayList, you can sort it using the Collections sort method. The sort method should sort the list first by decreasing age and then alphabetically (for people the same age).

下面是问题中提供的相同代码(Person 类)。

public class Person {
public String name;
public int age;
}

这是期中题,所以我必须手写代码。我想知道回答这个问题的有效且正确的方法是什么。非常感谢所有答案或意见。谢谢。

最佳答案

我想指出@Kevin Bowersox 的回答,他的答案按年龄升序排序,并且没有考虑姓名的第二种排序。用它替换compareTo可以解决这两个问题

@Override
public int compareTo(Person person)
{
int ageSort = new Integer(person.age).compareTo(this.age);

// If the ages aren't the same
if(ageSort != 0)
{
return ageSort;
}

// otherwise sort on name alphabetically
return name.compareTo(person.name);
}

关于java - 重写 ArrayList 类 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16181409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com