본문 바로가기
슬기로운 자바 개발자 생활/Java more

Java Comparable 메서드

by 슬기로운 동네 형 2017. 7. 27.
반응형

 

클래스내 멤버 변수로 sorting

Comparable을 구현해서 사용하면 된다.

 

public class SortExample {

    public static void main(String[] args){

        Member[] member = new Member[5];

        member[0] = new Member("짱구");
        member[1] = new Member("나늘이");
        member[2] = new Member("강한수");
        member[3] = new Member("다규라");
        member[4] = new Member("황현이");

        Arrays.sort(member);
        for(Member m : member){
            System.out.println("Member : " + m.toString()  );
        }


    }

}


class Member implements Comparable<Member>{

    private String name;

    public Member(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Member{" +
                "name='" + name + '\'' +
                '}';
    }

    @Override
    public int compareTo(Member o) {
        return name.compareTo(o.name);
    }
}

 

반응형

댓글