Programming/JAVA
[Java] 객체 정렬하기 (Comparable 인터페이스 이용)
코딩의성지
2021. 9. 7. 18:20
하이 ..
오늘은 자바에서 객체를 정렬하는 방법을 말씀드리려 한다.
예를 들어 키와 몸무게 정보를 가진 Player 클래스가 있다고 가정하자.
만약에 이 클래스의 키를 가지고 정렬을 하려면 아래와 같이 하면 된다.
import java.util.ArrayList;
import java.util.Collections;
public class Temp1 {
public static void main(String[] args) {
ArrayList<Player> players = new ArrayList<>();
players.add(new Player(168, 62));
players.add(new Player(157,50));
players.add(new Player(182,70));
players.add(new Player(176,80));
Collections.sort(players);
for(int i=0; i < players.size(); i++) {
System.out.println("player"+i+": " +players.get(i).height);
}
}
}
class Player implements Comparable<Player>{
int height;
int weight;
public Player(int height, int weight) {
this.height = height;
this.weight = weight;
}
@Override
public int compareTo(Player o) {
return o.height - this.height;
}
}
여기서 중요한 포인트가 하나 있는데 구현된 compareTo 메서드의 리턴값이 음수값이 나오도록 해줘야 큰 것부터 작은것으로 정렬되는 내림차순으로 정렬이 된다. 이점 잘 기억하자.
코드를 실행하면 아래와 같이 될 것이다.
끝.
반응형