2013-08-20 49 views
1

我有这个2维字符串数组。基于整数的2维字符串数组排序

2 10 BakerSarah D 
2 11 SmothersSally A 
2 12 SillySall C 
2 13 Viper B 
2 5 LouieChef B 
2 6 Lawson C 

每列都是字符串。现在我想在第二栏中进行分类。我曾尝试这个代码

void sortarray(final int index){ 
     Arrays.sort(data, new Comparator<Object[]>(){ 
      @Override 
      public int compare(Object[] o1, Object[] o2) { 
       String[] a = (String[])o1; 
       String[] b = (String[])o1; 
       return a[index].compareTo(b[index]); 
      } 
     }); 

    } 

,但这样做是为了给排序在

2 10 BakerSarah D 
    2 11 SmothersSally A 
    2 12 SillySall C 
    2 13 Viper B 
    2 5 LouieChef B 
    2 6 Lawson C 

。为什么这样 ?? 如何更改排序

2 5 LouieChef B 
2 6 Lawson C 
2 10 BakerSarah D 
2 11 SmothersSally A 
2 12 SillySall C 
2 13 Viper B 
+0

你想整数排序,但你的值仍然是一个字符串,你需要将它转换为整数,并比较整数 – x4rf41

回答

1

当比较返回0(即他们是平等的),那么你需要比较的另一个指标。我已经更新了你的代码来获得这个新索引 - index2。

void sortarray(final int index, final int index2){ 
    Arrays.sort(data, new Comparator<Object[]>(){ 
     @Override 
     public int compare(Object[] o1, Object[] o2) { 
      String[] a = (String[])o1; 
      String[] b = (String[])o1; 
      Integer i = a[index].compareTo(b[index]); 
      if (i == 0) { 
       return a[index2].compareTo(b[index2]); 
      } 
      return i; 
     } 
    }); 

} 

我假设(也许不正确),你想排序我的第一列,然后第二。如果它只是第二个然后尝试@ x4rf41说什么,并做一个Integer.valueOf将字符串转换为一个整数

虽然我会创建一个对象并实现Comparator这样你就可以在更多的OO办法。

+1

什么是索引2? – user2699538

+0

您需要将字符串转换为整数,然后排序才能工作 – x4rf41

+1

index2是您要排序的第二个索引。在这个例子中,它是包含5,6,10,... – RNJ

1

字符串具有自然的字典顺序。这意味着“10”在“5”之前。整数具有自然的数字顺序。所以,你应该改变你的字符串到数字和比较的数字:

Arrays.sort(data, new Comparator<Object[]>(){ 
    @Override 
    public int compare(Object[] o1, Object[] o2) { 
     String[] a = (String[])o1; 
     String[] b = (String[])o1; 
     if (index == 2) { // lexicographic order 
      return a[index].compareTo(b[index]); 
     } 
     else { // numeric order 
      int left = Integer.parseInt(a[index]); 
      int right = Integer.parseInt(b[index]); 
      return Integer.compare(left, right); 
     } 
    } 
}); 

请注意,这不会如果发生的,而不是一个String []牵你的信息,你用一个适当的类,有领域适当的类型:

public class Row { // choose a better name 
    private int field1; // choose a better name 
    private int field1; // choose a better name 
    private String name; 

    // constructor and getters omitted 
} 

Java是OO语言。使用对象。