1. isEquals 문제
연산자는 참조변수의 참조 값을 비교한다. 따라서 인스턴스에 저장되어 있는 값 자체를 비교하려면 별도의 방법을 사용해야 한다. 값 자체를 비교할 수 있도록 public boolean isEquals(IntNumber numObj) 메소드를 정의하시오.
class IntNumber
{
int num;
public IntNumber(int num)
{
this.num=num;
}
public boolean isEquals(IntNumber numObj)
{
return this.num == numObj.num;
}
}
class ObjectEquality
{
public static void main(String[] args)
{
IntNumber num1=new IntNumber(10);
IntNumber num2=new IntNumber(12);
IntNumber num3=new IntNumber(10);
if(num1.isEquals(num2))
System.out.println("num1과 num2는 동일한 정수");
else
System.out.println("num1과 num2는 다른 정수");
if(num1.isEquals(num3))
System.out.println("num1과 num3는 동일한 정수");
else
System.out.println("num1과 num3는 다른 정수");
}
}
2. Equals 문제
위의 1번을 object가 가진 equals 메소드를 오버라이딩 하여 구현하기
class IntNumber
{
int num;
public IntNumber(int num)
{
this.num=num;
}
public boolean equals(Object obj)
{
IntNumber other = (IntNumber)obj;
return this.num == other.num;
}
}
class ObjectEquality2
{
public static void main(String[] args)
{
IntNumber num1=new IntNumber(10);
IntNumber num2=new IntNumber(12);
IntNumber num3=new IntNumber(10);
if(num1.equals(num2))
System.out.println("num1과 num2는 동일한 정수");
else
System.out.println("num1과 num2는 다른 정수");
if(num1.equals(num3))
System.out.println("num1과 num3는 동일한 정수");
else
System.out.println("num1과 num3는 다른 정수");
}
}
3. Equals 문제
Rectangle 클래스에 내용 비교를 위한 메소드를 삽입하자. 그리고 이를 테스트하기 위한 예제를 작성하자.
class Point
{
int xPos, yPos;
public Point(int x, int y)
{
xPos = x;
yPos = y;
}
public void showPosition()
{
System.out.printf("[%d, %d]", xPos, yPos);
}
@Override
public boolean equals(Object obj) {
Point other = (Point)obj;
return this.xPos == other.xPos && this.yPos == other.yPos;
}
}
class Rectangle
{
Point upperLeft, lowerRight;
public Rectangle(int x1, int y1, int x2, int y2)
{
upperLeft = new Point(x1, y1);
lowerRight = new Point(x2, y2);
}
public void showPosition()
{
System.out.println("직사각형 위치정보...");
System.out.print("좌 상단 : ");
upperLeft.showPosition();
System.out.println("");
System.out.print("우 하단 : ");
lowerRight.showPosition();
System.out.println("\n");
}
@Override
public boolean equals(Object obj) {
Rectangle other = (Rectangle)obj;
return this.upperLeft.equals(other.upperLeft) && this.lowerRight.equals(other.lowerRight);
}
}
public class RectangleMain
{
public static void main(String[] args) {
Rectangle r1 = new Rectangle(1, 1, 2, 2);
Rectangle r2 = new Rectangle(1, 1, 2, 2);
Rectangle r3 = new Rectangle(1, 1, 3, 3);
System.out.println(r1.equals(r2));
System.out.println(r1.equals(r3));
}
}
'Java > Day25' 카테고리의 다른 글
[Java] Wrapper 클래스 (0) | 2021.12.07 |
---|---|
[Java] Clone 문제 (깊은 복사, 얕은 복사, 공변반환) (0) | 2021.12.07 |
[Java] 인스턴스 복사 clone 메소드 (0) | 2021.12.06 |