코딩테스트/Java

자료구조 관련 모음

알렉스 페레이라 2023. 4. 17. 16:43

헷갈릴만한 자료구조 관련 데이터들을 정리하기 위한 모음집,,

 

1.객체정렬(나와 비교)

객체를 정렬하기 위해서는 해당 클래스를 Comparable<T> 인터페이스를 구현해야한다. <T>는 해당객체.

그리고 Comparable인터페이스의 compareTo메소드를 override하여 구현하고 사용해야한다.

예)

class People implements Comparable<People> {
    String name;
    int height;
    int weight;

    public People(String name, int height, int weight) {
        this.name = name;
        this.height = height;
        this.weight = weight;
    }

    @Override
    public int compareTo(People people){
        if(this.height > people.height){
            return 1; // 내가 더 크다(오름차순 : 내가 뒤로, 내림차순 : 내가 앞으로)
        } else if (this.height == people.height) {
            return 0; //같다(유지)
        }else{
            return -1; //내가 더 작다(오름차순 : 내가 앞으로, 내림차순 : 내가 뒤로)
        }
        
        /**
        * 조건이 같다면, 분기처리를 통해 조건을 추가해 줄 수 있다.
        *ex) if(this.height == people.height){
        *		return this.weight - people.weight;
        *	 }else{
        *		return this.height - people.height;
        *	 }
        */
        
       
    }
}

 

 

2.객체정렬(두가지)

나와 다른 객체를 비교하여 정렬하기 위해서는 해당 클래스를 Comparable<T> 인터페이스를 구현했었다. 하지만 두 가지 객제를 서로 비교하기 위해서는 Comparator<T>객체를 사용해야한다. Comparator<T>는 함수형 인터페이스로, 소스 안에서 익명함수로 선언하고 사용이 가능하다.

예)

Arrays.sort(peopleArr, new Comparator<People>() {
            @Override
            public int compare(People people1, People people2) {
                return people1.height - people2.height; //첫번째 파라미터 - 두번째 파라미터 = 오름차순
                return people2.height - people1.height; //두번째 파라미터 - 첫번째 파라미터 = 내림차순
            }
});

'코딩테스트 > Java' 카테고리의 다른 글

Stream관련 모음  (0) 2023.04.17