ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Java] 자바 기본 API - Objects Class
    CSE/Java 2016. 1. 14. 14:19

    자바 기본 API는 여러 절로 구성되어 있습니다.



    Intro

    Object Class

    Objects Class

    System Class

    Class Class

    String Class

    StringTokenizer, StringBuffer, StringBuilder Class

    Regular Expression & Pattern Class

    Arrays Class

    Wrapper Class

    Math, Random Class

    Date, Calendar Class

    Format Class

    java.time Package





    Objects Class

     Object와 유사한 이름을 가진 java.util.Objects 클래스는 객체 비교, 해시코드 생성, null 여부, 객체 문자열 리턴 등의 연산을 수행하는 정적 메소드들로 구성된 Object의 유틸리티 클래스입니다. 다음은 Objects 클래스가 가지고 있는 정적 메소드들입니다.


     








     객체 비교(compare(T a, T b, Comparator<T> c)

      Object.compare(T a, T b, Comparator<T> c) 메소드는 두 객체를 비교자(comparator)로 비교하여 int 값을 리턴합니다. java.util.COmparator<T>는 제네릭 인터페이스 타입으로 두 객체를 비교하는 compare(T a, T b) 메소드가 정의되어 있습니다. compare() 메소드의 리턴 타입은 int 인데, a가 b보다 작으면 음수, 같으면 0, 크면 양수를 리턴하도록 구현 클래스를 만들어야 합니다.




    1
    2
    3
    public interface Comparator<T> {
        int compare(T a, T b)
    }
    cs




      다음 예제는 학생 객체에서 학생 번호로 비교하는 StudentComparator 구현 클래스를 작성한 것입니다. 



     * StudentComparator.java


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    package apiref;
     
    import java.util.Comparator;
     
    import apiref.ComparatorExam.Student;
     
    public class StudentComparator implements Comparator<Student> {
        @Override
        public int compare(Student a, Student b) {
            return Integer.compare(a.sno, b.sno);
        }
    }
     
    cs



     * ComparatorExam.java


    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
     
    package apiref;
     
    import java.util.Objects;
     
    public class ComparatorExam {
        public static void main(String[] args) {
            Student s1 = new Student(1);
            Student s2 = new Student(1);
            Student s3 = new Student(3);
     
            int result = Objects.compare(s1, s2, new StudentComparator());
            System.out.println(result);
            result = Objects.compare(s1, s3, new StudentComparator());
            System.out.println(result);
        }
     
        static class Student {
            int sno;
     
            Student(int sno) {
                this.sno = sno;
            }
        }
     
    }
     
    cs









     동등 비교(equals(), deepEquals())

      Objects.deepEquals(Object a, Object b)는 두 객체의 동등을 비교하는데, a와 b가 서로 다른 배열일 경우, 항목 값까지도 모두 같다면 true를 리턴합니다. 이것은 Arrays.deepEquals(Object a[], Object b[])와 동일합니다.












     해시코드 생성(hash(), hashCode())

      Objects.hash(Object... values) 메소드는 파라미터로 주어진 값들을 이용해서 해시 코드를 생성하는 역할을 하는데, 주어진 파라미터들로 배열을 생성하고 Arrays.hashCode(Object[])를 호출해서 해시코드를 얻고 이 값을 리턴합니다. 이 메소드는 클래스가 hashCode()를 재정의할 때 리턴값을 생성하기 위해 사용하면 좋습니다. 클래스가 여러 가지 필드를 가지고 있을 때 이 필드들로 부터 해시코드를 생성하게 되면 동일한 필드값을 가지는 객체는 동일한 해시코드를 가질 수 있습니다.



    1
    2
    3
    4
    @Override
    public int hashCode() {
        return Objects.hash(field1, field2, field3);
    }
    cs





      Objects.hashCode(Object o)는 파라미터로 주어진 객체의 해시코드를 리턴하기 때문에 o.hashCode()의 리턴값과 동일합니다. 차이점은 파라미터가 null이면 0을 리턴합니다. 다음 예제는 Student 객체의 해시코드를 생성하기 위해 Student의 필드인 sno(학생 번호)와 name을 파라미터로 해서 Objects.hash() 메소드를 호출했습니다. 학생 번호와 이름이 동일하다면 같은 해시 코드를 얻을 수 있다는 것을 보여줍니다.




     * HashCodeExam.java


    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
    package apiref;
     
    import java.util.Objects;
     
    public class HashCodeExam {
        public static void main(String[] args) {
            Student s1 = new Student(1"Jolie");
            Student s2 = new Student(1"Jolie");
            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);
            }
        }
    }
     
    cs







     객체 문자 정보(toString())

      Objects.toString()은 객체의 문자 정보를 리턴하는데, 다음 두 가지로 오버로딩되어 있습니다.








      첫 번째 파라미터가 not null이면 toString()으로 얻은 값을 리턴하고, null이면 "null" 또는 두 번째 파라미터값을 리턴합니다.



     * ToStringExam.java


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
     
    package apiref;
     
    import java.util.Objects;
     
    public class ToStringExam {
     
        public static void main(String[] args) {
            String str1 = "ACB";
            String str2 = null;
            
            System.out.println(Objects.toString(str1));
            System.out.println(Objects.toString(str2));
            System.out.println(Objects.toString(str2, "Null이 들어있습니다."));
        }
    }
     
    cs







     


     


     


     * 이 포스트은 서적 '이것이 자바다' 를 참고하여 작성한 포스트입니다.


    댓글

Designed by Tistory.