[Java] 객체간의 비교, 객체화

조히고닝·2023년 2월 27일
0

객체간의 비교

  • 동등성 비교 (둘의 스펙이 같은가?) equals
  • 동치성 비교 (둘이 같은 존재인가?) ==

자바에서 문자(char)는 숫자 취급이 된다.

String s = "abc"; = "a"+"b"+"c" 이다. 
String은 참조변수이기 때문에 객체의 비교는 equals 메서드를 이용해야함.
equals는 존재의 동일성을 비교하는 것이 아니라 객체가 가지는 값의 동등성을 비교. 

ex)
public static void main(String[] args) {
        String s= "heegwon";
        String s1 = "hee";
        String s2 = "gwon";
        
        System.out.println(s1 + s2);
        System.out.println(s==s1+s2);
        System.out.println(s.equals(s1+s2));
    }
  • 출력 결과:

모든 클래스는 Object 클래스를 상속받는다. (Object 클래스로부터 확장되었다.)

⇒ Object 클래스로 매개변수를 받으면 모든 형태를 받을 수 있음.

객체화

💡 변수에 대한 레퍼런스를 얻고 싶을 때 객체화 (박싱)를 할 수가 있다.

int a = 1; //기본형
Integer a =10;

Object obj= 10;
Object obj= (Object) new Integer(10);

//수동 박싱과 언박싱
public class Wrapper_Ex {
    public static void main(String[] args)  {
        Integer num = new Integer(17); // 박싱
        int n = num.intValue(); //언박싱
        System.out.println(n);
    }
}

//자동 박싱,언박싱
public class Wrapper_Ex {
    public static void main(String[] args)  {
        Integer num = 17; // 자동 박싱
        int n = num; //자동 언박싱
        System.out.println(n);
    }
}
  • 값비교 예제
public class Wrapper_Ex {
    public static void main(String[] args)  {
        Integer num = new Integer(10); //래퍼 클래스1
        Integer num2 = new Integer(10); //래퍼 클래스2
        int i = 10; //기본타입
		 
        System.out.println("래퍼클래스 == 기본타입 : "+(num == i)); //true
        System.out.println("래퍼클래스.equals(기본타입) : "+num.equals(i)); //true
        System.out.println("래퍼클래스 == 래퍼클래스 : "+(num == num2)); //false
        System.out.println("래퍼클래스.equals(래퍼클래스) : "+num.equals(num2)); //true
    }
}

0개의 댓글