Wednesday, June 6, 2012

Java Notes: Comparable dan Comparator

Comparable - java.lang package

@ this.compateTo(object o)
 same -> = 0
 less than -> <0
 greater than -> >0

Comparator - java.util package

@compare(object o1, object o2)
 same -> = 0
 less than -> <0
 greater than -> >0

Both are interface.
The different is "this" reference

Comparable is used by most java class like String, Date, Array, wrapper classes, etc
Comparable implement natural ordering of object.
If any object implements Comparable and collection of that object is either List or Array can be sorted automatically.

Oject that implement Comparable in Java can be used as keys in sorted map or elements in a sorted set. Eg. TreeSet, without specifiying any Comparator

Just collecting notes & sharing..
Please let me know if there are wrong statements in this article or a copy-paste one.

No comments:

Post a Comment