Java: ==, .equals(), and compareTo()

Comparison Primitives Objects
a == b, a != b Equal values Refer to the same object.
a.equals(b) N/A Compares values, if it’s defined for this class, as it is for most Java core classes. If it’s not defined for a (user) class, it behaves the same as ==.
a.compareTo(b) N/A Compares values. Class must implement the Comparable interface. All Java classes that have a natural ordering implement this (String, Double, BigInteger, …), but BigDecimal may not do what you expect. Comparable objects can be used by the Collections sort() method and data structures that implicitly sort (eg, TreeSet, TreeMap).
compareTo(a, b) N/A Compares values. Available only if the Comparator interface has been implemented, which is not the case for the Java classes. Typically used to define a comparator object that can be passed to Collections sort() method or ordered data structures.

최 재훈

블로그, 페이스북, 트위터 고성능 서버 엔진, 데이터베이스, 지속적인 통합 등 다양한 주제에 관심이 많다.
Close Menu