티스토리 뷰
StringUtils.equals()에 대해 알아보겠습니다.
먼저 equals()는 문자열을 비교하는 method입니다.
java Object Class들 중에서 자주 사용하고 있는 equals() method가 있습니다.
StringUtils에서도 equals() method를 사용할 수 있습니다.
StringUtils.class안에 method들 중 아래와 같은 method로 선언되어있는 걸 확인해 볼 수 있습니다.
public static boolean equals(final CharSequence cs1, final CharSequence cs2) {
if (cs1 == cs2) {
return true;
}
if (cs1 == null || cs2 == null) {
return false;
}
if (cs1.length() != cs2.length()) {
return false;
}
if (cs1 instanceof String && cs2 instanceof String) {
return cs1.equals(cs2);
}
// Step-wise comparison
final int length = cs1.length();
for (int i = 0; i < length; i++) {
if (cs1.charAt(i) != cs2.charAt(i)) {
return false;
}
}
return true;
}
StringUtils 클래스를 사용하기 위해 아래와 같이 import 해줍니다.
import org.apache.commons.lang3.StringUtils;
아래 예제를 통해 확인해야 할 부분은 String 변수에 null값이 있을 경우의 상황 있습니다.
StringUtils.equals()는 예외처리 없이 결과 false를 출력하고 다음 코드를 진행합니다.
java object class의 equals()는 java.lang.NullPointerException 예외처리를 하여 다음 코드를 진행하지 않습니다.
String a = null;
String b = "String";
String c = "String";
System.out.println(a.equals(b));
// 결과 : java.lang.NullPointerException
System.out.println(b.equals(a));
// 결과: false
System.out.println(b.equals(c));
// 결과: true
System.out.println(StringUtils.equals(a, b));
// 결과: false
System.out.println(StringUtils.equals(b, a));
// 결과: false
System.out.println(StringUtils.equals(b, c));
// 결과: true
StringUtils.equals()에 대해 알아보았습니다.
끝.
728x90
'Java' 카테고리의 다른 글
[Java] distinct() (0) | 2022.12.15 |
---|---|
[Java] Iterator() (0) | 2022.11.02 |
[Java] contains() (0) | 2022.06.30 |
[Spring] CollectionUtils.isEmpty() (0) | 2022.06.20 |
[Java] isEmpty() (0) | 2022.06.17 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- counter
- combinations
- If
- operators
- function
- Lower
- Built-in Functions
- permutations
- bool
- for
- zip
- Method
- Upper
- isalpha
- Lambda
- Python
- find
- index
- isdigit
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
글 보관함