【问题标题】:Collections.sort() not sorting single digit numberCollections.sort() 不排序单个数字
【发布时间】:2019-12-01 10:55:12
【问题描述】:

这是我的数据集[B,A,D,C,3,10,1,2,11,14]

我想这样排序[1,2,3,10,11,14,A,B,C,D]

当我使用关注时

public class ArenaModel implements Comparable<ArenaModel>{

    private String sectionName;

    @Override
    public int compareTo(ArenaModel o) {
        return sectionName.compareTo(o.sectionName);
    }

在主课中,我做以下事情。

 Collections.sort(arenaArrayList);

它进行排序,但单个数字没有排序,我得到以下结果。

[10,11,14,1,2,3,A,B,C,D]

【问题讨论】:

  • 是的,按字符串排序与按数字排序的结果不同。您可以编写一个自定义比较器来做正确的事情。
  • 作为@OleV.V.说过,从技术上讲,它是在对单个数字进行排序,只是不像你希望的那样。
  • 这些都存储为字符串吗?
  • @AshvinSharma:是的

标签: java android sorting comparable


【解决方案1】:

试试这个:

    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);
        }
    }

【讨论】:

  • 依赖异常可能是对大数据的昂贵操作。而是使用正则表达式匹配器或第三方库,如 Apache 等。
  • 它不能正确处理数字与字符的大小写以及相反的情况。 return sectionName.compareTo(o.sectionName); 在任何情况下都不起作用。
【解决方案2】:

假设字符串不包含混合值:字符和数字,您可以这样做:

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));
}

【讨论】:

    猜你喜欢
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2012-02-23
    • 2019-03-06
    相关资源
    最近更新 更多