繁体   English   中英

用负整数对一串数字排序

[英]Sorting a string of numbers with negative integers

我已经搜寻了两天,但没有成功,

现在我有7个整数(+和-)用逗号分隔的字符串。

我已经写了一个示例代码来解释。

        ArrayList<String> str = new ArrayList<String>();

        str.add("9,-9,21,23,28,29,35");
        str.add("18,18,-21,28,28,32,34");
        str.add("-11,-11,22,28,29,-30,31");
        str.add("8,-8,26,31,31,31,31");
        str.add("8,8,26,-32,25,29,35");
        str.add("10,9,-21,45,25,29,35");
        str.add("-11,59,21,25,25,-29,35");
        str.add("12,-9,21,55,25,29,15");
        str.add("9,9,21,25,25,-29,35");
        str.add("7,9,21,25,-35,25,35");
        str.add("4,-39,21,-15,25,-29,35");
        str.add("9,9,21,25,27,29,-35");
        str.add("10,9,21,35,25,39,15");
        str.add("8,-9,21,-25,25,29,-35");
        str.add("18,-9,21,-23,25,29,-35");

        Collections.sort(str);

这不会返回正确的排序数组。 它使用数字的第一位进行测试,然后进行排序。

但是我想要的是,排序必须基于字符串中的第一个数字。 仅当数字相同时(例如,字符串数组的第一个数字中有3个9),它才应检查那些数字(仅绑在一起的字符串)中的第二个数字,并进行相应的排序,依此类推。

结果应该是

9 , -9 , 21 , 23 , 28 , 29 , 35
9 , 9 , 21 , 25 , 25 , -29 , 35
9 , 9 , 21 , 25 , 27 , 29 , -35

有什么方法可以对此方法进行排序。 请让我知道是否有任何相关的答案。

提前致谢 。

您为所需的排序语义使用了错误的数据类型。 Java看到您要对字符串进行排序,因此按字典顺序对其进行排序,因为您没有告诉过它这样做。 Java是不介意的读者:)

而不是像“ 9,-9,21,23,28,29,35”那样尝试对字符串进行排序,而是像{9,9,-9,21,23,28,29,35 }。 您仍然必须为比较器编写自己的逻辑,但是由于您不必进行任何字符串解析,因此现在比较容易。

如果需要排序的数据以字符串格式到达您的程序,请尝试在',' split ','然后将字符串数组的每个组成部分解析为一个int,最后将它们全部转储到int数组或ArrayList中。

编写您的自定义排序逻辑并通过Collection#sort

Collections.sort(str, new Comparator<String>(){
                          public int compare(String str1, String str2){
                               // Write your logic
                               // @return a negative integer, zero, or a  
                              // positive integer as the first argument is less 
                              //  than, equal to, or greater than the second.
                          }
                      });

使用此比较方法作为sort(List list,Comparator c)的比较器:

Collections.sort(str, new Comparator<String>(){                    
    public int compare(String str1, String str2){
      int result = 0;
      int i = 0;
      String [] s1 = str1.split(",");
      String [] s2 = str2.split(",");
      while ((i < s1.length) && (i < s2.length) && (result == 0)){
        result = (Integer.parseInt(s1[i]) - Integer.parseInt(s2[i]));
        i++;        
      }
      return (result);
    }
});

您可以创建一个新的类NumberListString,以该字符串作为私有字段来实现Comparable接口。 提供适当的构造函数以及访问器/更改器。

现在,重写compareTo方法并提供用于此比较的逻辑。

然后使用Collections.sort(str)进行排序。 这将以所需方式对列表进行排序。

另外,您可以动态创建一个匿名比较器,并将其提供给Collections.sort方法。

注意:我将推荐第一种方法,因为它允许您抽象出可能需要在此特定类型的字符串上执行的其他操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM