[JAVA] ArrayList를 복사하고 정렬하고 싶을 때.
백준 문제 2822번을 풀기 위해 처음에 점수 입력을 Integer형 ArrayList에 담고
이를 또다른 ArrayList에 복사하여 오름차순 정렬 후 상위 5개 점수 이외에는 삭제.
그리고 처음 입력한 ArrayList와 복사해 정렬한 ArrayList를 비교해 동일한 점수의 항목이 있을 때
문제 번호를 출력하도록 했다.
뭔가 좀 더 단순하게 하고 싶었는데 ArrayList를 복사하는게 그냥 일반 변수 복사하듯이 되지 않는다는 것과
문제 번호를 출력해야 하는데서 하위 점수들을 삭제하다 보니 조금 복잡해졌다.
< 핵심코드 >
ArrayList<Integer> input = new ArrayList<>();
ArrayList<Integer> sortedList; // 복사해줄때 객체화 되기 때문에 선언만 해도 무방.
sortedList = (ArrayList<Integer>) input.clone();
Ascending ascending = new Ascending();
sortedList.sort(ascending); // 리스트를 sort하기 위해 따로 Comparator 구현이 필요.
class Ascending implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo((o2));
}
}
comparator 관련 참조하기 좋은 포스트
http://codeman77.tistory.com/4
ㄴ 감사합니다 :)