用负整数排序一串数字



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

现在我有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);

this不能返回正确排序的数组。它以数字的第一个数字进行测试,然后继续排序。

但是我想要的是,排序必须基于字符串中的第一个数字。只有当数字是相同的(假设字符串数组的第一个数字中有三个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

使用这个比较方法作为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);
    }
});

编写自定义排序逻辑并通过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.
                          }
                      });

您可以创建一个新的类,例如NumberListString实现Comparable接口,并将此字符串作为私有字段。提供适当的构造函数以及访问器/变量

现在重写compareTo方法,并为这个比较提供逻辑。

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

或者,您可以动态地创建一个匿名比较器,并将其提供给集合。排序方法。

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

最新更新