
개요
Apex의 List 클래스는 Apex 코딩 시 정말 자주 사용하는 자료구조로써 많은 기능들이 내장되어 있어 이를 편리하게 사용할 수 있다.
그 중, List안에 들어있는 요소들을 오름차순으로 정렬하는 기능을 sort() 메서드로 제공을 한다.
sort()로 정렬할 수 있는 타입은 다음과 같다:
- primitive type (Integer나 String 같은)
- SelectOption
- Standard or custom objects
primitive type에 대한 정렬은 직관적으로 이해할 수 있으므로 자세한 설명은 생략한다.
SelectOption과 sObject들은 정렬 시 몇가지 내부적인 단계들이 있는데, 이에 대한 설명은 다른 포스팅에서 한다.
무튼, List의 sort()로 대부분의 케이스를 만족시킬 수 있긴 하지만, 간혹 우리가 직접 만든 Apex class 타입에 대한 List를 정렬해야 할 때가 있다. 예를 들면, API로 외부와 데이터를 주고 받을 때, 사용할 수 있는 JSON 개체 클래스가 있다.
이런 상황에서 우리는 정렬을 해야할 Apex class에 Comparable 인터페이스를 구현하여 문제를 해결할 수 있다.
Comparable 사용 예시
먼저, Apex class의 리스트에서 아무런 조치 없이 sort()를 사용했을 때를 보자.
Dog라는 클래스를 생성하였고, Dog를 타입으로 가지는 List를 생성 후 Dog 인스턴스를 3개 생성하여 집어넣었다.
class Dog {
public String name;
public Integer age;
public Boolean isAlive;
public Dog(String name, Integer age, Boolean isAlive) {
this.name = name;
this.age = age;
this.isAlive = isAlive;
}
}
List<Dog> dogs = new List<Dog>();
dogs.add(new Dog('Cola', 4, true));
dogs.add(new Dog('Absolute', 6, true));
dogs.add(new Dog('Zondo', 2, true));
dogs.sort();
위 코드를 그대로 복사하여 Developer console에서 실행시키면 아래와 같은 에러메세지를 볼 수 있다.
System.ListException: One or more of the items in this list is not Comparable.
왜 에러가 나는 것일까? 당연하게도, 정렬을 시키려는 기준이 없기 때문이다.
그리하여, 아래처럼 Comparable 인터페이스를 구현한다. compareTo() 메서드의 함수 몸체를 작성하면 되며, 반환값은 Integer로 내부에 대소를 비교할 수 있는 기준과 로직을 작성해주면 된다. 반환값에서 음수는 현재 대상이 비교 대상보다 크기가 작다는 것을 의미하며, 양수는 반대로 더 크다는 것을 의미한다. 0은 둘이 크기가 같다 라는 것을 의미한다.
class Dog implements Comparable {
public String name;
public Integer age;
public Boolean isAlive;
public Dog(String name, Integer age, Boolean isAlive) {
this.name = name;
this.age = age;
this.isAlive = isAlive;
}
// Implement the compareTo() method
public Integer compareTo(Object compareTo) {
Dog compareToDog = (Dog)compareTo;
if (this.name == compareToDog.name) return 0;
if (this.name > compareToDog.name) return 1;
return -1;
}
}
이후 아래처럼 sort() 메서드 호출 전/후로 디버그 메세지를 찍어보자.
List<Dog> dogs = new List<Dog>();
dogs.add(new Dog('Cola', 4, true));
dogs.add(new Dog('Absolute', 6, true));
dogs.add(new Dog('Zondo', 2, true));
System.debug(dogs);
dogs.sort();
System.debug(dogs);
아래와 같이 name필드를 기준으로 잘 오름차순 정렬된 것을 볼 수 있다.

정리
Comparable 인터페이스는 구현 대상의 Apex class의 인스턴스끼리 "비교"가 가능하도록 비교 로직 및 기준을 작성할 수 있게 해주는 도구이다. 이를 이용해 List.sort() 메서드로 기정의한 비교 로직을 따라 정렬이 가능하게 만들 수 있다.
'Salesforce > Salesforce Dev' 카테고리의 다른 글
| (Secure Apex) User Mode Database Operations (0) | 2024.05.27 |
|---|---|
| Comparator Interface and Collator Class (0) | 2024.05.24 |
| Apex Null Coalescing Operator (0) | 2024.05.12 |
| Apex Test Data Loading with csv (0) | 2024.04.16 |
| Salesforce Apex Debug Log (세일즈포스 Apex 디버그 로그) (0) | 2024.04.01 |