본문 바로가기
Effective JAVA 2판

Effective Java Item12 Comparable 구현을 고려하다.

by BroBroBro 2015. 5. 4.

--page1

구현을 고려하는 이유?

Comparable인터페이스를 구현하는 객체들은 자연적순서(natural ordering)게 된다.


Comparable을 구현한 객체들은 배열을 정렬하는 것은 아래의 예제처럼 아주 간단하다.라고 책에서 말하고있음.

Arrays.sort(a)

3장은 모든객체의 공통메서드들을 다루고 있다.

지금까지 본 equals, hashcode, toString, clone등은 모두 String에 정의가 되어있지 않던가?

그럼 Comparable도 한번 봐보도록 하자 어떻게 String가 쓰고 있는지..

1
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public interface Comparable<T> {
 
아래와 같은 주석을 달고 있더라 
 /**
     * Compares this object with the specified object for order.  Returns a
     * negative integer, zero, or a positive integer as this object is less
     * than, equal to, or greater than the specified object.
…….생략
     * @param   o the object to be compared.
     * @return  a negative integer, zero, or a positive integer as this object
     *          is less than, equal to, or greater than the specified object.
     *
     * @throws NullPointerException if the specified object is null
     * @throws ClassCastException if the specified object's type prevents it
     *         from being compared to this object.
     */
    public int compareTo(T o);
cs

이정도만 알면 될듯… other = T o

this other 보다 작으면 음수

this other 와 같다면 0

this other 보다 크면 양수


--page2

자바 플랫폼 라이브러리에 포함된 거의 모든 값 클래스(value class)
Comparable
인터페이스를 구현하고 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class TestOrder {
 
    public static void main(String[] args) {
        Set<String> s = new TreeSet<String>();
        s.add("b");
        s.add("a");
        System.out.println(s); // in order numbers
 
        List<Integer> list = new ArrayList<Integer>();
 
        list.add(1);
        list.add(3);
        list.add(2);
        System.out.println(list);
 
        Object[] objArray = list.toArray();
        Arrays.sort(objArray);
        for (Object a : objArray) {
            System.out.print(a + ", ");
        }
 
    }
}
cs

Result :

[a, b]

[1, 3, 2]

1, 2, 3, 


--page3

여기에도 CompareTo구현할때의 몇가지 규칙이 있는데 결국 equals와 비슷합니다.(궂이 언급을 안할께요^^;) 단 한가지다른것이 있어요

BigDecimal(“1.0”)new BigDecimal(“1.00”)로 만든 객체가 있다면 이는 같다고 해야한다는거죠.


중복값이 없어야하는 Collection 에서 사용할때

equals도 비교하지만 compareto까지도 비교해야지만 정확한 비교를 할수있다는것이고 자신의 객체가 그러한 성격이라면 compareto에서 처리를 해줘야 합니다.

실제로 자바에서도 HashSet객체에 위의 1.01.00넣었을때 값은 1개만 들어가있습니다.

--page4