Language/Java

How do I compare strings in Java? | Stack Overflow 정리

이웃비 2020. 12. 11. 17:22

 

본 내용은 Stack Overflow의 한국어 번역이 아니며, 개인적인 공부를 위해 Stack Overflow 질의를 정리한 내용입니다

 

 

 질문 

Java에서 문자열을 어떻게 비교해야 합니까?

I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.

Is == bad? When should it and should it not be used? What's the difference?

 


저는 문자열 비교를 위해 지금까지 ==를 사용해왔습니다. 그런데 버그가 났습니다. 그래서 .equals()로 바꿨더니 해결되었습니다.

'=='를 쓰는것은 안좋습니까? 언제 사용해야 하고 사용하지 않아야 합니까? .equals와 뭐가 다릅니까?

 

 

 답변 

 

== tests for reference equality (whether they are the same object).

.equals() tests for value equality (whether they are logically "equal").

Objects.equals() checks for null before calling .equals() so you don't have to (available as of JDK7, also available in Guava).

Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().


 

'==' 는 참조가 동일한지 테스트합니다(같은 메모리를 참조하는지)

.'equals()' 는 값이 동일한지 테스트합니다(논리적으로 값이 같은지) 

Object.equals() 를 사용하면 equals()를 호출하기 전에 null을 체크할 수 있습니다. 그러므로 그럴 필요 없습니다(JDK7, Guava에서도 이용할수 있습니다)

-> Object.equals() 를 사용하면 null이어도 비교해주므로 equals()보다 이 함수를 사용하는게 좋다는 말 같음.

Object.equals()와 equals() 뭐가 다른가?

 

따라서 두 문자열이 같은지 알고싶다면 Object.equals()를 사용하십시오.

 

// These two have the same value
new String("test").equals("test") // --> true 

// ... but they are not the same object
new String("test") == "test" // --> false 

// ... neither are these
new String("test") == new String("test") // --> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
"test" == "test" // --> true 

// ... string literals are concatenated by the compiler
// and the results are interned.
"test" == "te" + "st" // --> true

// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
Objects.equals(null, null) // --> true

 

You almost always want to use Objects.equals(). In the rare situation where you know you're dealing with interned strings, you can use ==.


 

당신은 Objects.equals()을 사용하게 될 것입니다. 드물게 interned string을 사용하는 경우에, '=='를 사용할 수 있습니다.

interned string이란?

 

 

From JLS 3.10.5. String Literals:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Similar examples can also be found in JLS 3.10.5-1.

 

 


 

** 문자열 리터럴에 대한 설명. String.intern을 사용하는 경우와 이유에 대해 기술했다. 다음 포스팅 참고.

 

 

 

Other Methods To Consider

String.equalsIgnoreCase() value equality that ignores case.

String.contentEquals() compares the content of the String with the content of any CharSequence (available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.

 


고려해 볼 다른 메소드String.equalsIgnoreCase() : equals() 와 같으나, 대소문자 구분 안함String.contentEquals()  : string문자열과 매개변수 문자열의 값이 일치하면 true를 반환한다. string 객체를 StringBuffer / StringBuilder / Char Array 객체들과 비교할 수 있다.아래 예시 참고

public class StringMethod {
	public static void main(String[] args) {
    	String a = "aa";
        String b = "aa";
        StringBuffer c = new StringBuffer("aa")
        
        // equals()를 사용할 때
        System.out.println(a.equals(b)); // true
        System.out.println(a.equals(c)); // false
        
        // contentEquals() 를 사용할 때
        System.out.println(a.contentEquals(b)); // true
        System.out.println(a.contentEquals(c)); // true
    }
}