본문 바로가기

PROGRAMMING/JAVA

'==' , compareTo(), equals() - 서로간의 차이점에 대해 알아보자

연산자 ==, String 메서드 equals와 compareTo.


이 셋은 모두 비교를 할 때 쓰이는 연산자와 메서드이다.


그렇다면 과연 이 셋의 차이점을 무엇일까?


일단 API를 보며 이 셋을 분석해보자.


1) compareTo

public int compareTo(String anotherString)


Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this Stringobject lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns exactly when the equals(Object) method would return true.

This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, 

compareTo returns the difference of the two character values at position k in the two string -- that is, the value:


this.charAt(k) - anotherString.charAt(k)


If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:


this.length()-anotherString.length()


Specified by:

compareTo in interface Comparable<String>

Parameters:

anotherString-the String to be compared

Returns:

the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.


빨간색 부분을 집중해서 보자.


compareTo 메서드는 알파벳 순으로 두개의 문자열을 비교하는 메서드다.


두 문자열의 같은 인덱스의 각 값이 서로 같은지 비교한다. 


A라는 String 문자열이 있고 A와 비교하는 B라는 String 문자열이 있다고 생각해보자.


A와 B의 문자열이 같다면 메서드의 return 값은 0이다.


A와 B의 문자열이 다르다면 메서드의 return 값은 문자 간의 차이값이 된다.


소스를 통해 한 번 볼까.



String형 변수 A에 compareTo 라는 문자를 넣어주고, B에는 값과 주소값이 같도록 선언하고 C에는 값은 같으나 주소값이 다르도록 선언해주었다.


이 상태에서 A와 B, A와 C를 비교한 결과 둘 다 0이 나오는 것을 볼 수 있다. 이것으로 단순 값만 비교했을 때 같으면 0을 return한다는 사실을 알았다.


이번에는 값이 다를 경우를 한번 보자.



A를 compareTo로 B와 비교를 하면 32이라는 값이 나온다. A와 B를 비교했을 때 같은 위치에서 서로 다른 값이 처음 있는 부분은 't'와 'T'이다.


A를 기준으로 메서드를 사용한 것이기 때문에 (t의 아스키 코드(116)-T의 아스키 코드(84))를 하면 32가 나온다.


반면 A와 C를 비교를 하면 -2라는 값이 나온다. A와 C를 비교했을 때 같은 위치에서 서로 다른 값이 처음 있는 부분은 'c'와 'e'이다.


아까와 같이 A를 기준으로 하여 (c의 아스키 코드(99)-e의 아스키 코드(101))를 하면 -2가 나온다.


정리하자면 기준 String 객체가 매개 변수 String 객체와 같으면 0을 return, 기준 String 객체가 매개 변수 String 객체보다 알파벳 순으로 앞이라면 음수, 뒤라면 양수가 나오는 것이다.


2) equals

public boolean equals(Object anObject)
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Overrides:
equals in class Object
Parameters:
anObject - The object to compare this String against
Returns:
true if the given object represents a String equivalent to this string, false otherwise
See Also:
compareTo(String), equalsIgnoreCase(String)

equals 메서드는 boolean 값을 return 한다. 같으면 true, 다르면 false를 출력한다.


직접 코드를 보자.



equals 메서드는 위의 예제로 보다시피, 주소값에 상관없이 값이 같으면 true를 출력하고 값이 다르면 false를 출력한다.


3) == 연산자


== 연산자 역시 비교하는 값들이 서로 같은지 다른지를 판별하는 연산자이다. return은 boolean값으로 true 혹은 false를 출력한다.


예시를 일단 보자.


== 연산자는 equals 메서드와는 다르게 주소값으로 판별한다. 값이 다르면 당연히 false를 출력하고 값이 같더라도 주소값이 다르면 false를 출력한다.


최종 정리해보자.


compareTo 메서드, equals 메서드, == 연산자는 두 값을 비교할 때 사용한다.


compareTo 메서드는 주소값에 상관없이 값만을 가지고 비교하며 같을 땐 0을, 다를 땐 같은 인덱스에서 다른 문자가 처음 나온 문자들의 차이의 값을 return 한다.


equals 메서드는 주소값에 상관없이 값만을 가지고 비교하며 같을 땐 true, 다를 땐 false를 return 한다.


== 연산자는 값이 다르면 당연히 false, 값은 같아도 주소값이 다르다면 false, 값과 주소값이 모두 같으면 true를 return 한다.


'PROGRAMMING > JAVA' 카테고리의 다른 글

[ JAVA 정복 ] Thread(쓰레드) - 1  (0) 2018.10.10
[ JAVA 정복 ] java.lang 패키지와 유용한 클래스  (0) 2018.10.08
잠깐) 보수법  (2) 2013.02.25
4. 상속(inheritance)  (0) 2013.02.25
3. 배열(Array)  (0) 2013.02.25