본문 바로가기

Study/Java

[JAVA][tip] equals 사용시 주의할 점(equals 비교 오류)

반응형
enum type을 사용하다 보면 열거값을 체크하기 위해 다음처럼 사용하는 경우가 많다.
public class B {
	public enum Test {
		AA("aa", "a의 설명")
		, BB("bb", "b의 설명")
		, CC("cc", "c의 설명")
		, DD("dd", "d의 설명")
		, EE("ee", "e의 설명")
		, FF("ff", "f의 설명")
		, GG("gg", "g의 설명")
		, HH("hh", "h의 설명");
		
		private String name;
		private String description;

		Test(String name, String description) {
			this.name = name;
			this.description = description;
		}

		public String value() {
			return name;
		}
		
		public static String getDescription(String name) {		//name에 해당하는 description을 가져오기 위한 구문
			for (Test test : Test.values()) {
				if (name.equals(test.name)) return test.description;
			}
			return null;
		}
	}
}
위와 같이 사용하게 되면 아래와 같이 호출하는 경우 java.lang.NullPointerException 에러가 발생한다.
String description = Test.getDescription(null);
String에 null값이 들어간 경우 static method로 equals가 존재하지만 null 값은 말 그대로 객체가 존재하지 않는 값이기 대문에 지원가능한 메소드가 없기 때문이다. 따라서 위와 같은 경우 아래처럼 바꿔주어야 한다.
public static String getDescription(String name) {		//name에 해당하는 description을 가져오기 위한 구문
	for (Test test : Test.values()) {
		if (test.name.equals(name)) return test.description;
	}
	return null;
}
앞부분에 null이 들어오지 않는다고 보장된 enum type을 위치하고 이와 매개변수를 비교하는 것이다.

enum이 아니더라도 equals 비교 메소드의 앞부분에 null이 들어올 가능성이 있는 String 객체는 위치시키지 않는 것이 좋다.
반응형