티스토리 뷰

IT/JAVA

[JAVA] 객체 비교

긍정탁 2017. 7. 14. 10:50

 

- 객체 레퍼런스의 동일성 비교 == 연산자  이용

 

- 객체 내용 비교    

 - 서로 다른 두객체가 같은 내용물인지 비교

 - boolean equals(Object obj) 이용

 

 

소스코드

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
29
30
31
32
33
34
35
36
37
38
package today;
 
class Point{
    int x,y;
    Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
    public boolean equals(Point p){
        if(x==p.x&&y==p.y)
            return true;
        else
            return false;
    }
}
 
public class todays170714 {
        
    
    public static void main(String args[]){
    Point a =new Point(2,3);
        Point b =new Point(2,3);
        Point c =new Point(3,4);
        
        if(a==b)
            System.out.println("a==b");
        if(a.equals(b))
        {
            System.out.println("a is equal to b");
        }
        if(a.equals(c))
        {
            System.out.println("a is equal to c");
        }
    }
}
 
cs

 

boolean type의 함수를 이용하여 각각의 Point 형 객체들의 비교를 간단히 할수 있다.

점 a는 점 b와 위치가 동일하므로 a is equal to b가 출력 된다.

 

출력화면

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 29 30 31