2012년 10월 4일 목요일

Array 정렬

Arrays.sort() 함수를 이용해 배열을 정렬할 수 있다.

Comparator 를 구현하여 정렬 방식을 조절할 수 있다.

예) 파일 목록을 디렉토리, 파일 순으로 정렬하면서 알파벳 순으로 정렬하는 코드

File[] files = file.listFiles();

Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
boolean d1 = f1.isDirectory();
boolean d2 = f2.isDirectory();
if (d1 && !d2) {
return -1;
} else if (!d1 && d2) {
return 1;
} else {
return f1.getName().toUpperCase().compareTo(f2.getName().toUpperCase());
}
}
});

정리) compare() 함수에 -1 을 리턴하면 앞의 값을 앞으로 1 을 리턴하면 뒤의 값을 앞으로 0 을 리턴하면 변경 없이 정렬이 된다.

댓글 없음:

댓글 쓰기