[英]Collections.sort() not sorting single digit number
This is my data set [B,A,D,C,3,10,1,2,11,14]
这是我的数据集
[B,A,D,C,3,10,1,2,11,14]
I want to sort it like this [1,2,3,10,11,14,A,B,C,D]
我想这样排序
[1,2,3,10,11,14,A,B,C,D]
When i use following当我使用以下
public class ArenaModel implements Comparable<ArenaModel>{
private String sectionName;
@Override
public int compareTo(ArenaModel o) {
return sectionName.compareTo(o.sectionName);
}
In Main class, i do following.在主课上,我做以下。
Collections.sort(arenaArrayList);
It does sorting but single digit numbers do not get sort, and i get following result.它进行排序,但单位数没有排序,我得到以下结果。
[10,11,14,1,2,3,A,B,C,D]
Try this:尝试这个:
public class ArenaModel implements Comparable<ArenaModel>{
private String sectionName;
@Override
public int compareTo(ArenaModel o) {
try {
Integer s1 = Integer.valueOf(sectionName);
Integer s2 = Integer.valueOf(o.sectionName);
return s1.compareTo(s2);
} catch (NumberFormatException e) {
// Not an integer
}
return sectionName.compareTo(o.sectionName);
}
}
Supposing that the String contains no mixed values : characters and digits, you could do that :假设 String 不包含混合值:字符和数字,您可以这样做:
import static java.lang.Character.isAlphabetic;
import static java.lang.Integer.parseInt;
@Override
public int compareTo(ArenaModel o) {
String sectionOther = o.getSectionName();
String sectionThis = getSectionName();
// 1) handle comparisons with any alphabetic value
boolean isThisAlphabetic = isAlphabetic(sectionThis);
boolean isOtherAlphabetic = isAlphabetic(sectionOther);
// move the alphabet value at the end
if (isThisAlphabetic && !isOtherAlphabetic){
return 1;
}
// move the alphabet value at the end
if (!isThisAlphabetic && isOtherAlphabetic){
return -1;
}
// compare String values
if (isThisAlphabetic && isOtherAlphabetic){
return sectionThis.compareTo(sectionOther);
}
// 2) By eliminatation, you have two integer values
return Integer.compare(parseInt(sectionThis), parseInt(sectionOther));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.