본문 바로가기

삽질하기/JAVA

Comparable 구현하여 사용자객체 정렬하기

반응형
public class UserObject implements Comparable<UserObject> {
	
	private int priority;
	
	public UserObject(int priority) {
		this.priority = priority;
	}
	
	public int compareTo(UserObject o) {
		if(this.priority < o.priority) {
			return -1;
		} else if (this.priority > o.priority) {
			return 1;
		} else {
			return 0;
		}
	}
	
	public String toString() {
		return "priority : " + this.priority;
	}
}
public class CompareTest {
	public static void main(String[] args) {
		UserObject[] arr = {
			new UserObject(5),
			new UserObject(2),
			new UserObject(4),
			new UserObject(6),
			new UserObject(1),
			new UserObject(7),
			new UserObject(3),
		};
		
		System.out.println("정렬 전 출력");
		print(arr);
		
		System.out.println("정렬후 출력");
		Arrays.sort(arr);
		print(arr);
		
	}
	
	public static void print(UserObject[] arr) {
		for(int i=0; i<arr.length; i++) {
			System.out.println(arr[i].toString());
		}
	}
}

출력결과
정렬 전 출력
priority : 5
priority : 2
priority : 4
priority : 6
priority : 1
priority : 7
priority : 3
정렬후 출력
priority : 1
priority : 2
priority : 3
priority : 4
priority : 5
priority : 6
priority : 7