我正在使用比较器对IRC用户列表进行排序,[
和_
等字符位于@
之前。我该如何防止这种情况?我希望以这些字符开头的用户成为常规用户。比较器现在看起来:
public class UserListSorter implements Comparator<String> {
// Get the Collator for the current locale.
private Collator collator = Collator.getInstance();
@Override // The comparator that implements the abovementioned.
public int compare(String o1, String o2) { // Compare these users.
int compare = compareString(o1.substring(0, 2), o2.substring(0, 2)); // Get the user group of the users (@,+,())
if (compare == 0) { // If both are in the same group, sort by
return compareString(o1, o2); // their name only.
}
return compare; // Else, return a positive value stating
} // that @ and + holds a higher value than ().
private int compareString(String o1, String o2) { // Compares the users alphabetically, ignoring small
return collator.compare(o1, o2); // and capital letters. Used as a basis for sorting algo.
}
}
感谢。
答案 0 :(得分:1)
未经测试,但应该这样做:
if (o1.charAt(0) == '@' && o2.charAt(0) != '@') return 2;
else if (o1.charAt(0) != '@' && o2.charAt(0) == '@') return -2;
else if (o1.charAt(0) == '+' && o2.charAt(0) != '+') return 1;
else if (o1.charAt(0) != '+' && o2.charAt(0) == '+') return -1;
else return o1.compareTo(o2);
编辑:当前行为是以@
&gt;开头的名称+
&gt;任何其他。
答案 1 :(得分:0)
我建议在这里引入更高级别的抽象,并采取更多的OO方法。
假设我们创建了一个表示IRC用户的对象,我们称之为IRCUser
:
class IRCUser implements Comparable<IRCUser>
{
private IRCRole ircRole;
private String nickName; //full nickname
public int compareTo(IRCUser otherUser)
{
//Implementation
}
}
然后创建一个枚举,描述用户可以在特定IRC频道上授予的角色,例如:
public enum IRCRole
{
STANDARD("", 2), PRIVILEDGED("+",1) , OP("@",0)
IRCRole(String nickNamePrefix, int priority)
{
this.nickNamePrefix = nickNamePrefix;
this.priority = priority;
}
private String nickNamePrefix;
private int priority;
}
现在,我们的IRCUser的compareTo方法可能通过比较this
用户(确切地说是角色priority
)与作为参数传递的用户角色之后的角色开始。做简单的字符串比较。怎么样?