Java에서 정렬은 java.util.Collections 클래스의 sort() 메소드를 이용한다.
(https://docs.oracle.com/javase/8/docs/api/)
- Sorts the specified list into ascending order, according to the natural ordering of its elements.
- 정렬한다, 지정된 리스트를, 오름차순으로, 요소의 지정된 리스트를. 요소의 자연스러운 순서에 따라.
- Sorts the specified list according to the order induced by the specified comparator.
- 정렬한다, 지정된 리스트를, 순서에 따라, 지정된 comparatoer에 의해 유도된다.
sort()의 매개변수 타입은 List<T>로 제네릭을 받는다.
이 때 T는 Comparable 인터페이스를 구현해야만 한다.
예제와 함께 보자.
public class sort { public static void main(String[] args) { List<String> nameList = new ArrayList<>(); nameList.add("Park"); nameList.add("Choi"); nameList.add("Kim"); System.out.println("- 정렬 전" + nameList); Collections.sort(nameList); System.out.println("- 정렬 후" + nameList); } }
String 클래스는 Comparable<T> 인터페이스를 구현하고있고, CharSequence
Compable<T> 인터페이스를 보면,
Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.
sort에 의해 자동으로 정렬될 수 있다고 설명되어있다.
참고한 블로그를 보면, String 클래스가 Comparable 인터페이스를 사전편찬순으로 정렬되도록 구현하고있다고 나와있는데, API에서 어느 부분인지 잘 찾지 못하겠다. (영어와 api 탐색스킬의 부재...)
public class sortTest02 { class Person{ String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } } public static void main(String[] args) { List<Person> nameList = new ArrayList<>(); nameList.add(new Person("Park", 30)); nameList.add(new Person("Choi", 26)); nameList.add(new Person("Kim", 29)); System.out.println("- 정렬 전" + nameList); Collections.sort(nameList); //에러가 나는 부분 System.out.println("- 정렬 후" + nameList); } }
Person 클래스는 Compareable 인터페이스를 구현하지 않았기 때문에 에러가 발생한다.
즉, compareTo(T obj)메소드를 오버리이딩해야 List<Person>을 정렬할 수 있다.
이런식으로 compareTo를 오버라이드해야 사용할 수 있다. (예제는 나이순으로 정렬)
사용자가 원하는 임의의 정렬기준대로 정렬하고 싶으면, 직접 정의해주면 된다. 이 때 기준이 되는 것이 Comparator 인터페이스를 구현하는 것이다.(위에서 한 방식은 Comparable 인터페이스 구현이다. 잘 구분하자.) compare() 메소드를 오버라이딩 해주면 된다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | package study.collections; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class sortTest03 { static class Person{ String name; int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person[name="+ name + ", age=" + age +"]"; } } static class nameLengthCompare implements Comparator<Person>{ @Override public int compare(Person p1, Person p2) { return p1.getName().length() > p2.getName().length() ? 1 : p1.getName().length() < p2.getName().length() ? -1 : 0; } } public static void main(String[] args) { List<Person> nameList = new ArrayList<>(); nameList.add(new Person("Parkkk", 30)); nameList.add(new Person("Choi", 26)); nameList.add(new Person("Kim", 29)); System.out.println("- 정렬 전" + nameList); Collections.sort(nameList, new nameLengthCompare()); System.out.println("- 정렬 후" + nameList); } } | cs |
(https://colorscripter.com/) 에서 소스코드를 컬러화해주더라.
문제는, 블로그 작성할 때 이 코드가 너무 길다.
(마크다운 방식으로 소스코드 작성할 때, >(앵글브래킷)를 자꾸 소스코드로 인식해서 생기는 문제점이 있다. 아직 마크다운 방식에 익숙하지 않아서 그런가? 참 불편하다. 어떻게 소스코드를 이쁘게 업로드할 수 있을지 알아봐야겠다. 당장은 컬러스크립트가 최선인 것 같다.)
출처 https://wjheo.tistory.com/entry/Java-%EC%A0%95%EB%A0%AC%EB%B0%A9%EB%B2%95-Collectionssort