[Java 자바] 11. 기본 API 클래스 ③ Objects 클래스
11-4. Objects 클래스
객체 비교, 해시코드 생성, null 여부, 객체 문자열 리턴 등의 연산을 수행하는 정적 메소드로 구성된 Object의 유틸리티 클래스
리턴 타입 | 메소드(매개 변수) | 설명 |
int | compare(T a, T b, Comparator<T> c) | 두 객체 a와 b를 Comparator를 사용하여 비교 |
boolean | deepEquals(Object a, Object b) | 두 객체의 깊은 비교(배열의 항목까지 비교) |
boolean | equals(Object a, Object b) | 두 객체의 얕은 비교(번지만 비교) |
int | hash(Object... values) | 매개값이 저장된 배열의 해시코드 생성 |
int | hashCode(Object o) | 객체의 해시코드 생성 |
boolean | isNull(Object obj) | 객체가 null인지 조사 |
boolean | nonNull(Object obj) | 객체가 null이 아닌지 조사 |
T | requireNonNull(T obj) | 객체가 null인 경우 예외 발생 |
T | requireNonNull(T obj, String msg) | 객체가 null인 경우 예외 발생(주어진 예외 메시지 포함) |
T | requireNonNull(T obj, Supplier<String> messageSupplier) |
객체가 null인 경우 예외 발생(람다식이 만든 예외 메시지 포함) |
String | toString(Object o) | 객체의 toString() 리턴값 리턴 |
String | toString(Object o, String nullDefault) | 객체의 toString() 리턴값 리턴, 첫 번째 매개값이 null일 경우 두 번째 매개값 리턴 |
11-4-1. 객체 비교 (compare(T a, T b, Comparator<T> c))
Objects.compare(T a, T b, Comparator<T> c) 메소드는 두 객체를 비교자(Comparator)로 비교하여 int 값 리턴
//StudentComparator.java
import java.util.Comparator;
import objects1.Compare.Student;
public class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student a, Student b) {
if(a.sno < b.sno) return -1;
else if(a.sno == b.sno)return 0;
else return 1;
}
}
//CompareTest.java
import java.util.Comparator;
import java.util.Objects;
public class CompareTest {
public static void main(String[] args) {
Student s1 = new Student(1);
Student s2 = new Student(1);
Student s3 = new Student(2);
int result = Objects.compare(s1, s2, new StudentComparator()); // 0
System.out.println(result);
result = Objects.compare(s1, s3, new StudentComparator()); // -1
System.out.println(result);
}
static class Student {
int sno;
Student(int sno){
this.sno = sno;
}
}
static class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return Integer.compare(o1.sno, o2.sno);
}
}
}
11-4-2. 동등 비교 (equals()와 deepEquals())
1) Objects.euqals(Object a, Object b)
- a와 b가 모두 null일 경우 true를 리턴함
- a와 b가 null이 아닐 경우 a.equals(b) 결과를 리턴
a | b | Objects.equals(a, b) |
not null | not null | a.equals(b) |
null | not null | false |
not null | null | false |
null | null | true |
2) Objects.deepEquals(Object a, Object b)
- a와 b가 서로 다른 배열일 경우, 항목 값이 모두 같다면 true를 리턴
a | b | Objects.deepEquals(a, b) |
not null (not array) | not null (not array) | a.equals(b) |
not null (array) | not null (array) | Arrays.deepEquals(a,b) |
not null | null | false |
null | not null | false |
null | null | true |
package objects1;
import java.util.Arrays;
import java.util.Objects;
public class Equals {
public static void main(String[] args) {
Integer o1 = 1000;
Integer o2 = 1000;
System.out.println(Objects.equals(o1, o2)); // true
System.out.println(Objects.equals(o1, null)); // false
System.out.println(Objects.equals(null, o2)); // false
System.out.println(Objects.equals(null, null)); // true
System.out.println(Objects.deepEquals(o1, o2) + "\n"); // true
Integer[] arr1 = {1, 2};
Integer[] arr2 = {1, 2};
System.out.println(Objects.equals(arr1, arr2)); // false
System.out.println(Objects.deepEquals(arr1, arr2)); // true
System.out.println(Arrays.deepEquals(arr1,arr2)); // true
System.out.println(Objects.equals(null, arr2)); // false
System.out.println(Objects.equals(arr1, null)); // false
System.out.println(Objects.equals(null, null)); // true
}
}
11-4-3. 해시코드 생성 (hash(), hashCode())
Objects.hash(Object... values) 메소드는 매개값으로 주어진 값들을 이용해서 해시 코드를 생성하는 역할을 함
- 주어진 매개값들로 배열을 생성하고 Arrays.hashCode(Object[])를 호출해서 해시코드를 얻어 이 값을 리턴
- hashCode()를 재정의할 때 리턴 값을 생성하기 위해 사용하면 좋음
- 클래스가 여러 가지 필드를 가지고 있을 때 이 필드들로부터 해시코드를 생성하면
동일한 필드값을 가지는 객체는 동일한 해시코드를 가질 수 있음
- 매개값이 null이면 0을 리턴
@Override
public int hashCode() {
return Objects.hash(field1, field2, field3);
}
package objects1;
import java.util.Objects;
public class HashCodeTest {
public static void main(String[] args) {
Student s1 = new Student(1, "Erin");
Student s2 = new Student(1, "Erin");
System.out.println(s1.hashCode()); // 동일한 해시코드 리턴.
System.out.println(Objects.hashCode(s2)); // 동일한 해시코드 리턴.
}
static class Student {
int sno;
String name;
Student(int sno, String name) {
this.sno = sno;
this.name = name;
}
@Override
public int hashCode() {
return Objects.hash(sno, name);
}
}
}
11-4-4. 널 여부 조사(isNull(), nonNull(), requireNonNull())
- Objects.isNull(Object obj)는 매개값이 null일 경우 true 리턴
- Objects.nonNull(Object obj)는 매개값이 not null일 경우 true 리턴
- Objects.requireNonNull()은 아래와 같이 세 가지로 오버로딩
리턴 타입 | 메소드(매개 변수) | 설명 |
T | requireNonNull(T obj) | not null → obj null → NullPointerException |
T | requireNonNull(T obj, String message) | not null → obj null → NullPointerException(message) |
T | require NonNull(T obj, Supplier<String> msgSupplier) |
not null → obj null → NullPointerException(msgSupplier.get()) |
package objects1;
import java.util.Objects;
public class NullTest {
public static void main(String[] args) {
String str1 = "Erin";
String str2 = null;
System.out.println(Objects.requireNonNull(str1)); // Erin
try {
String name = Objects.requireNonNull(str2);
} catch(Exception e) {
System.out.println(e.getMessage()); // null
}
try {
String name = Objects.requireNonNull(str2, "이름이 없습니다.");
} catch(Exception e) {
System.out.println(e.getMessage()); // 이름이 없습니다.
}
try {
String name = Objects.requireNonNull(str2, ()->"람다식, 이름이 없습니다.");
} catch(Exception e) {
System.out.println(e.getMessage()); // 람다식, 이름이 없습니다.
}
}
}
11-4-5. 객체 문자 정보(toString())
Objects.toString()은 객체의 문자 정보를 리턴, 다음 두 가지로 오버로딩되어 있음
리턴 타입 | 메소드(매개변수) | 설명 |
String | toString(Object o) | not null → o.toString() null → "null" |
String | toString(Object o, String nullDefault) | not null → o.toString() null → nullDefault |
public class ToString {
public static void main(String[] args) {
String str1 = "Erin";
String str2 = null;
System.out.println(Objects.toString(str1)); // Erin
System.out.println(Objects.toString(str2)); // null
System.out.println(Objects.toString(str2, "이름이 없습니다.")); // 이름이 없습니다.
}
}