본문 바로가기

IT/ETC

Comparable vs Comparator

반응형

Comparable is a interface you need to implement to a Object where a specific compare standard has to be defined by overriding compareTo method.

compareTo needs to be returned as an int value, + for moving up a list, - for moving down, 0 for staying at the same place.

Wrapper type data does NOT need comparable interface to be compared since all Wrapper class already has been implemented with a Comparable interface. String, char are compared by unicode, numbers are obviously compared by numbers. You could implement Comparable on an object class if standard comparing method does not suit your needs. 

Comparator on the other hand is another interface used with purpose of for Collections.sort or Arrays.sort to directly assign comparable standards. anonymous class(?) is assigned on the back of collections.sort or arrays.sort and overrides compare method. the compare method is also an int return method and is same as compareTo method but the difference is number of parameter. compare requires two while compareTo only requires one. This is very simple to understand because you implement comparable to a object class, comparing class variable to parameter while for comparator you do not have a class object to compare to so you need two parameter to be compared. 

Collections.sort performs merge sort algorithm

 

 

반응형

'IT > ETC' 카테고리의 다른 글

이것이 자바다 노트1  (0) 2019.12.09
Garbage Collector  (0) 2019.12.01
Algorithm time complexity  (2) 2019.12.01
자바 메모리 구조  (0) 2019.11.23
various query  (0) 2019.11.14