Object와 유사한 이름을 가진 java.util.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 message) | 객체가 null인 경우 예외 발생 (주어진 예외 메시지 포함) |
T | requireNonNull(T obj, Supplier<String> messgeSupplire) | 객체가 null인 경우 예외 발생(람다식이 만든 예외 메시지 포함) |
String | toString(Object o) | 객체의 toString() 리턴값 리턴 |
String | toString(Object o, String nullDefault) | 객체의 toString() 리턴값 리턴, 첫번째 매개값이 null 일 경우 두번째 매개값 리턴 |
객체 비교(compare(T a, T b , Comparator<T> c))
objects.compare(T a, T b Comparetor<T> c) 메소드는 두객체를 비교자(Comparator)로 비교해서 int 값 을 리턴,
*java.util.Comparator<T>는 제네릭 인터페이스 타입으로 두객체를 비교하는 compare(T a, T b) 메소드가 정의 됨
compare() 메소드의 리턴 타입은 int, a가 b 보다 작으면 음수, 같으면 0, 크면 양수를 리턴하도록 구현 클래스를 만들어야함
public interface Comprator<T> {
int compare(T a, T b);
}
ex)
public class CompareExample{
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());
System.out.println(result);
result = Object.compare(s1, s3, new StudentComparator());
System.out.println(result);
}
static class Student {
int sno;
Student(int sno){
this.sno = sno;
}
}
static class studentComparator implemnets Comaprator<Student>{
@Override
public int compare(Student o1, Student o2){
/*
if(o1.sno<o2.sno) return -1
else if(o1.sno == o2.sno) return 0;
else return 1;
*/
return Integer.compare(o1.sno, o2,sno);
}
}
}
동등 비교(equals()와 deepEquals())
Objects.equal(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 |
Objects.deepEquals(Object a, Object b) 역시 두 객체의 동등을 비교,
a와 b가 서로 다른 배열일경우, 항목값이 모두 같다면 true 리턴
Arrays.deepEquals(Object[] a, Object[] b)와 동일
a | b | Objects.deepEquals(a, b) |
not null(not array) | not null(not array) | a.equals(b)의 리턴값 |
not null(arrray) | not null(array) | Arrays.deepEquals(a, b)의 리턴값 |
not null | null | false |
null | not null | false |
null | null | true |
해시코드 생성(hash(), hashCode())
Object.hash(Object.. values) 메소드는 매개값으로 주어진 값들을 이용해서 해시코드를 생성하는 역할을 한다
주어진 매개값들로 배열을 생성하고 Arrays.hashCode(Object[])를 호출 해시코드를 얻고 이값을 리턴한다
이 메소드는 클래스가 hashCode()를 재정의할때 리턴값을 생성하기 위해 사용하면 좋다.
클래스가 여러가지 필드를 가지고 있을때 이 필드들로부터 해시코드를 생성하게 되면
동일한 필드값을 가지는 객체는 동일한 해시코드를 가질수 있음
@Override
public int hashCode(){
return Objects.hash(field1, field2, field3);
}
Objects.hashCode(Object o)는 매개값으로 주어진 객체의 해시코드를 리턴하기 때문에 o.hashCode()의 리턴 값과 동일
차이점은 매개값이 null이면 0을 리턴,
널 여부 조사(isNull(), nonNull(), requireNonNull())
Objects.isNUll(Object obj)는 매개값이 null일 경우 true를 리턴한다.
반대로 nonNull(Object obj)는 매개값이 not null 일 경우 true를 리턴
requireNonull()는 다음 세가지로 오버로딩 되어 있다
리턴타입 | 메소드(매개변수) | 설명 |
T | requireNonNull(T obj) | not null -> obj null -> NullPointerExceotion |
T | requireNonNull(T obj, String message) | not null -> obj null -> NullPointerException(message) |
T | requireNonnull(T obj, Supplier<Stirng> msgSupplier) | not null -> obj null -> NullPointerExceptin(msgSupplier.get()) |
첫번째 매개값이 not null 이면 첫 번쨰 매개값을 리턴하고, null이면 모두 NullPointerException을 발생 시킨다.
두번째 매개값은 NullPointerException의 예외 메시지를 제공 한다.
객체 문자 정보(toString())
Objects.toString()dms 객체의 문자 정보를 리턴,
리턴 타입 | 메소드(매개변수) | 설명 |
String | toString(Object o) | not null -> o.toString() null -> "null" |
String | toString(Obejct o, String nullDefault) | not null -> o.toString() null -> nullDefault |
첫 번째 매개값이 not null 이면 toStirng()으로 얻은 값을 리턴, null 이면 "null" 또는 두번째 매개값 nullDefault 리턴
'Back-end > 이것이 자바다[신용권 한빛미디어]' 카테고리의 다른 글
Class 클래스 (0) | 2021.10.23 |
---|---|
System 클래스 (0) | 2021.10.23 |
Object 클래스 (0) | 2021.10.22 |
java.lang 과 java.util 패키지 (0) | 2021.10.22 |
자바 API 도큐먼트 (0) | 2021.10.22 |