CompareTo

민지킴·2021년 5월 9일
0

Test 코드

class Test implements Comparable<Test>{

    int first;
    int second;
    int third;

    public Test(int first, int second, int third){
        this.first=first;
        this.second= second;
        this.third = third;

    }

    public int compareTo(Test o){
        return o.first - first;
    }

    public String toString(){
        return "first : "+first+", second : "+second+", third : "+third;
    }

}

1. 단순 비교해야할것이 하나인 경우

내림차순

 public int compareTo(Test o){
        return o.first - first;
    }

오름차순

 public int compareTo(Test o){
        return first - o.first;
    }

2. return 값을 정확히 명시하는 경우

오름차순

public int compareTo(Test o){
        if(third>o.third){
            return 1;
        }else{
            return -1;
        }
    }

public int compareTo(Test o){
        if(o.third>third){
            return -1;
        }else{
            return 1;
        }
    }


내림차순

public int compareTo(Test o){
        if(third>o.third){
            return -1;
        }else{
            return 1;
        }
    }

public int compareTo(Test o){
        if(o.third>third){
            return 1;
        }else{
            return -1;
        }
    }
profile
하루하루는 성실하게 인생 전체는 되는대로

0개의 댓글