관리 메뉴

MOMONOTE

Collections.sort 본문

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Animal {
	    String name;
	    int age;
	    
	    public Animal(String name, int age) {
	        this.name = name;
	        this.age = age;
	    }
	    
	    public String getName() {
	        return this.name;
	    }
	    
	    public int getAge() {
	        return this.age;
	    }
	
    public static void main (String[] args) {
    	ArrayList<Animal> list = new ArrayList<Animal>();
        
        list.add(new Animal("cat", 3));
        list.add(new Animal("dog", 6));
        list.add(new Animal("horse", 2));
        list.add(new Animal("snake", 10));

        
        Collections.sort(list, new Comparator<Animal>() {
            @Override
            public int compare(Animal a1, Animal a2) {
                if (a1.getAge() < a2.getAge()) {
                    return -1;
                } else if (a1.getAge() > a2.getAge()) {
                    return 1;
                }
                return 0;
            }
        });
 
  
        for (Animal a : list) {
            System.out.println(a.getAge());
        }
    }
}
// 결과
// 2
// 3
// 6
// 10




 

 

 

 

    Collections.sort(list, new Comparator<Animal>() {
            @Override
            public int compare(Animal a1, Animal a2) {
                if (a1.getAge() < a2.getAge()) {
                    return -1;
                } else if (a1.getAge() > a2.getAge()) {
                    return 1;
                }
                return 0;
            }
        });

이 코드에서 a1과 a2의 age를 비교한다. 

a2의 age가 더 크다? 음수인 -1 리턴한다. 그리고 자리이동은 없다. 

 

a1의 age가 더크다? 양수인 1을 리턴한다. 그러면 a1이 뒤로 간다. 

 

결과적으로 오름차순으로 정렬됨. 

 

음수 또는 0이면 객체의 자리가 그대로 유지되며, 양수인 경우에는 두 객체의 자리가 변경된다. 

더 자세한건 이곳을 참고하자.
https://gmlwjd9405.github.io/2018/09/06/java-comparable-and-comparator.html

Comments