2011-09-06 12 views
5

Excel의 스프레드 시트처럼 .csv 파일 형식으로 읽었습니다. 파일에 의해 결정되는 특정 수의 열이 있으며 .split(",") 메서드를 사용하여 각 줄을 문자열 배열로 읽습니다. 그런 다음 배열 목록에 넣으면 특정 크기를 지정하지 않고 모든 문자열 배열을 유지할 수 있습니다. 그러나 Collections.sort()을 사용하여 배열 목록을 정렬하면 프로그램이 중단됩니다. 문제는 무엇이 될 수 있습니까? 여기에 내 코드 정렬하는 것입니다배열 배열 정렬 [] 배열

Collections.sort(stringList, new Comparator <String[]>() { 
    public int compare(String[] strings, String[] otherStrings) { 
     return -1 * (strings[sortNum].compareTo(otherStrings[sortNum])); 
    } 
}); 
+1

여기서 'sortNum'은 어디에서 왔습니까? –

+2

"휴식"이란 무엇입니까? 그것은 어디에서 깨지지 않습니까? 어떤 오류가 발생합니까? 당신은 무엇을 기대 했습니까? 모든 행에'sortNum' + 1 셀이 있습니까? –

+0

'sortNum '이란 무엇입니까? – guardianpt

답변

5

두 점 :

  • 비교를 반대로 -1 compare의 결과를 곱하지 마십시오. Integer.MIN_VALUE * -1은 여전히 ​​Integer.MIN_VALUE입니다. 대신, 비교 자체의 순서를 반대로하십시오.
  • 내 생각 엔 입니다. 실제로에 충분한 열이없는 행이 있습니다. 아마 그걸 마지막에 놓아야 할까? 같은

뭔가 :

Collections.sort(stringList, new Comparator <String[]>() { 
    public int compare(String[] x1, String[] x2) { 
     if (x1.length > sortNum && x2.length > sortNum) { 
      return x2[sortNum].compareTo(x1[sortNum]); 
     } 
     if (x1.length > sortNum) { 
      return 1; 
     } 
     if (x2.length > sortNum) { 
      return -1; 
     } 
     return x2.length - x1.length; 
    } 
}); 

또는 만들기 위해 먼저 목록을 필터링 절대적으로 모든 행이 충분히 열이 있는지 확인.

+0

이것은 아름답게 작동했습니다. 고맙습니다 – nathpilland

1

음, 두 문자열 [sortNum] 또는 otherStrings은 [sortNum] 아웃 오브 바운드 될 수 있습니다. 이를 방지하려면 몇 가지 검사를해야합니다. 또한 문자열 [sortNum] 또는 otherStrings [sortNum]은 null 일 수 있습니다. 당신이이 두 가지 중 하나에 달려 있다고 확신합니다. 호출 스택은 무엇을 나타 냅니까?

0

'sortNum'변수와 관련하여 클로저 문제가있을 것으로 생각됩니다. 어떤 지침에 대해서는 Jon Skeet's closure article을 참조하십시오. C#의 클로저는 여전히 관련성이 있어야합니다. 이 문제가 없다고해도 좋은 읽을 거리입니다. :)

0

당신은 빈 "세포"에 대한 기본값을 제공 할 수 있습니다

  public int compare(String[] strings, String[] otherStrings) { 
       String one, other; 
       one = other = ""; // default value 
       if (sortNum<strings.length && strings[sortNum] != null) { 
        one = strings[sortNum]; 
       } 
       if (sortNum<otherStrings.length && otherStrings[sortNum] != null) { 
        other = otherStrings[sortNum]; 
       } 
       return -1 * (one.compareTo(other)); 
      } 
1

생성자와이

먼저 클래스 비교기를 사용해보십시오 :

public class MyStringArrayComparator implements Comparator<String[]>{ 

     Integer sortNum; 

     public MyStringComparator(Integer index) { 
       sortNum = index; 
     } 

     @Override 
     public int compare(String[] strings, String[] otherStrings) { 
       return -1*(strings[sortNum].compareTo(otherStrings[sortNum])); 
     } 
} 

및 코드에서

Collections.sort(stringList,new MyStringArrayComparator<String[]>(index)); 

희망이 당신을 위해

0

누군가가 여러 열에 정렬을해야 할 경우 코드를 공유하십시오.

public final class ArrayComparatorWithIndex<T extends Comparable<T>> implements Comparator<T[]> 
{ 
    private final int[] indexToSort; 

    public ArrayComparatorWitIndex(int[] indexToSort) 
    {   
     if(indexToSort == null || indexToSort.length == 0){ 
      throw new IllegalArgumentException("Index to use for sorting cannot be null or empty."); 
     } 
     this.indexToSort = indexToSort; 
    } 

    @Override 
    public int compare(T[] str, T[] otherStr) 
    { 
     int result= 0; 
     for (int index : indexToSort) 
     { 
      result= str[index].compareTo(otherStr[index]); 
      if (result != 0){ 
       break; 
      } 
     } 
     return result; 
    } 
} 

//Example how to use it: 
int[] indexForSorting= new int[] { 1, 3 }; 
Collections.sort(stringList, new ArrayComparator<String>(indexForSorting));