예제 9월 1일 Arrays.sort() 메서드를 이용한 객체의 정렬
2009. 9. 1. 17:36
package net.jeongsam.excise; class SortTest implements Comparable{ int a, b; public SortTest() { this(5, 5); } public SortTest(int a, int b) { this.a = a; this.b = b; } /** * 두 SortTest 타입의 객체간의 비교는 객체가 가지고 있는 멤버변수의 * 합을 기준으로 비교. */ @Override public int compareTo(SortTest obj) { int sum = a + b; return ((sum < (obj.a + obj.b)) ? -1 : (sum == (obj.a + obj.b) ? 0 : 1)); } @Override public String toString() { return ("a : " + a + ", b : " + b); } }
package net.jeongsam.excise; import java.util.Arrays; class SortMain { public SortTest[] st; public SortMain() { st = new SortTest[5]; st[0] = new SortTest(1, 3); st[1] = new SortTest(2, 3); st[2] = new SortTest(1, 2); st[3] = new SortTest(2, 1); st[4] = new SortTest(3, 3); } public static void main(String[] args) { SortMain main = new SortMain(); System.out.println("--- 정렬전 ---"); for (SortTest s : main.st) { System.out.println(s); } Arrays.sort(main.st); System.out.println("--- 정렬후 ---"); for (SortTest s : main.st) { System.out.println(s); } } }