유블로그

[Java] Collections.sort() 본문

Java

[Java] Collections.sort()

yujeong kang 2020. 8. 23. 20:21
class Number implements Comparable<Number> {
	int a;
	Number(int a){
		this.a = a;
	}
	
	@Override
	public int compareTo(Number num) {
		return this.a - num.a;
	}
}

public class Test01 {
	public static void main(String[] args) {
		List<Number> list = new ArrayList<>();
		list.add(new Number(3));
		list.add(new Number(0));
		list.add(new Number(15));
		list.add(new Number(11));
		list.add(new Number(5));
		
		for(Number n : list) System.out.println(n.a);
		
		Collections.sort(list, new Comparator<Number>() {

			@Override
			public int compare(Number o1, Number o2) {
				return o1.a - o2.a;
			}
		
		});
		
		for(Number n : list) System.out.println(n.a);
		
	}
}