gpt4 book ai didi

java - 根据两个条件对列表进行排序

转载 作者:行者123 更新时间:2023-11-29 07:43:11 24 4
gpt4 key购买 nike

所以,我不知道是否有一个优雅的解决方案,但这里是。我想对列表进行排序,但该列表包含三种类型的项目。我想要的是类型 A 按字母顺序排列在顶部,类型 B 和 C 位于底部并按字母顺序排列(类型 B 和 C 将合并)。

这是我的代码:

public int compareTo(Friendship another) {
if(this.getType().equals(TypeA) &&
another.getType().equals(TypeA)){ //if they are both type A, just sort based on user name

return this.getUsername().compareTo(
another.getUsername());
}
else if(this.getType.equals(TypeA)){
return -1;
}
else if(another.getType().equals(TypeA)){
return 1;
}
else{ //this will be hit if they are either Type B or C, then just sort based on username
return this.getUsername().compareTo(
another.getUsername());
}
}

编辑:抱歉,我应该更好地解释这一点。问题是上面的代码不起作用。据我所见,该列表似乎没有正确排序。<罢工>由于某种原因,TypeA 列表的顺序与我想要的相反(Z -> A)。而 TypeB & C 列表只排序了一半。所以我假设我的代码中存在错误。如果您需要更多信息,请告诉我。

EDIT2:对样本进行了更多测试,看起来字符串根本没有被排序。我都做了

this.getUsername().compareTo(
another.getUsername());

another.getUsername().compareTo(
this.getUsername());

编辑 3:你们是对的。我的代码中的其他地方有一个错误(这是不相关的)。抱歉......在这种情况下也不知道该怎么办。我该给谁正确的答案?

最佳答案

如果我是你,我不会改变结构,只会优化这点

public int compareTo(Friendship another) {


if(!this.getType().equals(another.getType()){
//if type are not equal, so we might have at most one A

if(this.getType.equals(TypeA)){ //on left side
return -1;
}

if(another.getType().equals(TypeA)){ //or, on rightside
return 1;
}
}
//or we have on both sides or neither side
return this.getUsername().compareTo(
another.getUsername());
}

关于java - 根据两个条件对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28159148/

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