Java
정렬
Sun-Koo
2023. 3. 10. 16:39
컬렉션을 사용하는 이유 중의 하나는 정렬과 같은 데이터와 관련된 작업을 하기 위해서다.
import java.util.*;
class Computer implements Comparable{ // Comparable 을 구현해야 정렬할 수 있다.
int serial;
String owner;
Computer(int serial, String owner){
this.serial = serial;
this.owner = owner;
}
public int compareTo(Object o) {
// Serial 값으로 비교
return this.serial - ((Computer)o).serial;
}
public String toString(){
return serial+" "+owner;
}
}
public class CollectionsDemo {
public static void main(String[] args) {
List<Computer> computers = new ArrayList<Computer>();
computers.add(new Computer(500, "egoing"));
computers.add(new Computer(200, "leezche"));
computers.add(new Computer(3233, "graphittie"));
Iterator i = computers.iterator();
System.out.println("before");
while(i.hasNext()){
System.out.println(i.next());
}
Collections.sort(computers);
System.out.println("\nafter");
i = computers.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
}
}
실행 결과
before
500 egoing
200 leezche
3233 graphittie
after
200 leezche
500 egoing
3233 graphittie
메소드 sort는 그 중의 하나로 List의 정렬을 수행한다.
sort의 인자인 list는 데이터 타입이 List이다. 즉 메소드 sort는 List 형식의 컬렉션을 지원한다는 것을 알 수 있다.
메소드 sort를 실행하면 내부적으로 compareTo를 실행하고 그 결과에 따라서 객체의 선후 관계를 판별하게 된다.