[필기정리]Day19 - equals(), clone() 등

SW/Java

2020. 7. 6. 12:16

# 자바 가상머신의 메모리 분류방식

영역 내용
메소드 영역(method area) 메소드의 바이트코드, static 변수
스택 영역(stack area) 지역변수, 매개변수
힙 영역(heap area) 인스턴스

 

# runFinalization : 개체를 수거하고 싶을 때 사용하는 메소드

   하지만 가비지컬렉션 강제 호출하지 않는 게 좋다.

 

#equals

 매개변수로 객체의 참조변수를 받아서 비교하여 그 결과를 boolean값으로 알려주는 역할의 메소드이다.

 Object 클래스는 equals 메소드를 가지고 있다.

 기본적으로 equals를 메소드 오버라이딩한다고 개발자들이 생각한다.

public boolean equals(Object obj)
{ 
	return (this == obj);
}    

 

- equals와 ==의 차이점   

   equals 메소드는 비교하고자 하는 대상의 내용 자체를 비교

    == 연산자는 비교하고자 하는 대상의 주소값을 비교

 

Q. == 연산자는 참조변수의 참조 값을 비교한다. 

    따라서 인스턴스에 저장되어 있는 값 자체를 비교하려면 별도의 방법을 사용해야 한다.

    값 자체를 비교할 수 있도록 public boolean isEquals(IntNumber numObj) 메소드를 정의하시오.

class IntNumber
{
	int num;
	
	public IntNumber(int num)
	{
		this.num=num;
	}
	public boolean isEquals(IntNumber numObj)
	{
	}
}
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는 다른 정수");
		
	}
}

 

A.

class IntNumber
{
	int num;
	
	public IntNumber(int num)
	{
		this.num=num;
	}
	public boolean isEquals(IntNumber numObj)
	{
    	if(this.num==numobj.num)
        	return true;
		else
        	return false;
	}
}
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는 다른 정수");
		
	}
}

 

Q. 위의 문제를 Object 클래스의 equals 라는 메소드를 이용하여 구현하시오.

A.

class IntNumber
{
	int num;
	
	public IntNumber(int num)
	{
		this.num=num;
	}
	
	public boolean equals(Object obj)
	{
		if(this.num==((IntNumber)obj).num)
			return true;
		else
			return false;
	}
}
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는 다른 정수");
	}
}

 

 

 Q. 아래의 소스를 가지고 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);
	}
}
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");
	}
}

A.

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;
		if(xPos==other.xPos && yPos==other.yPos) return true;
		else return false;
	}
	
}
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;
		if(upperLeft.equals(other.upperLeft) && lowerRight.equals(other.lowerRight))
			return true;
		else return false;
	}
}
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(2, 2, 3, 3);
		if(r1.equals(r2)) System.out.println("좌표값이 서로 같다.");
		else System.out.println("좌표값이 서로 다르다.");
		if(r1.equals(r3)) System.out.println("좌표값이 서로 같다.");
		else System.out.println("좌표값이 서로 다르다.");
	}
}

 

- String

  new를 사용해서 객체 생성하는 경우 기존에 똑같은 문자열이 있어도 객체를 새로 생성한다.

 

class StringEquals
{
	String srt1 = new String("Hi my String");
    String srt2 = new String("Hi my String");
    
    if(str1 == str2)
    	System.out.print

 

#clone : 객체를 복사하는 메소드

 clone 메소드를 사용하기 위해선 cloneable이라는 인터페이스를 구현해줘야 한다.

 cloneable 인터페이스는 아무런 내용이 들어 있지 않은 빈 인터페이스이지만,

 객체를 복사하고자 할 때 이 인터페이스를 구현하지 않으면 CloneNotSupportedException이 발생한다.

 clone을 사용하고자 하면 try catch를 통해 예외처리 해야 한다.

 

- 얕은 복사(shallow copy) : 주소값이 있는 해당 객체 자체만 복사하는 것

  깊은 복사(deep copy) : 해당 객체와 참조하고 있는 객체까지 복사하는 것

 

Q. 폴더에 있는 것은 얕은 복사가 된 소스이다. 

    이것을 깊은 복사가 된 소스로 변경하시오.

org.showPosition() 하면
직사각형 위치정보...
좌 상단: [2, 2] 
우 하단:[7, 7]
cpy.showPosition() 하면
직사각형 위치정보...
좌 상단: [2, 2] 
우 하단:[7, 7]  이라고 출력된다.

이것을 다음의 형태로 출력되게 바꾸자.
직사각형 위치정보...
좌 상단: [2, 2] 
우 하단:[7, 7]
직사각형 위치정보...
좌 상단: [1, 1] 
우 하단:[9, 9]

 

class Point implements Cloneable
{
	private int xPos;
	private int yPos;
	
	public Point(int x, int y)
	{
		xPos=x;
		yPos=y;
	}
	public void showPosition()
	{
		System.out.printf("[%d, %d]", xPos, yPos);
	}
	public void changePos(int x, int y)
	{
		xPos=x;
		yPos=y;
	}
	public Object clone() throws CloneNotSupportedException
	{
		return super.clone();
	}
}
class Rectangle implements Cloneable
{
	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");
	}
	public void changePos(int x1, int y1, int x2, int y2)
	{
		upperLeft.changePos(x1, y1);
		lowerRight.changePos(x2, y2);
	}
	public Object clone() throws CloneNotSupportedException
	{
		return super.clone();
	}
}
class ShallowCopy
{	
	public static void main(String[] args)
	{
		Rectangle org=new Rectangle(1, 1, 9, 9);
		Rectangle cpy;
		
		try
		{
			cpy=(Rectangle)org.clone();
			org.changePos(2, 2, 7, 7);
			org.showPosition();
			cpy.showPosition();
		}
		catch(CloneNotSupportedException e)
		{
			e.printStackTrace();
		}
	}
}

 

A.

class Point implements Cloneable
{
	private int xPos;
	private int yPos;
	
	public Point(int x, int y)
	{
		xPos=x;
		yPos=y;
	}
	public void showPosition()
	{
		System.out.printf("[%d, %d]", xPos, yPos);
	}
	public void changePos(int x, int y)
	{
		xPos=x;
		yPos=y;
	}
	public Object clone() throws CloneNotSupportedException
	{
		return super.clone();
	}
}
class Rectangle implements Cloneable
{
	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");
	}
	public void changePos(int x1, int y1, int x2, int y2)
	{
		upperLeft.changePos(x1, y1);
		lowerRight.changePos(x2, y2);
	}
	public Object clone() throws CloneNotSupportedException
	{
		Rectangle cpy = (Rectangle)super.clone();
		cpy.upperLeft = (Point)upperLeft.clone();
		cpy.lowerRight = (Point)lowerRight.clone();
		return cpy;
	}
}
class ShallowCopy
{	
	public static void main(String[] args)
	{
		Rectangle org=new Rectangle(1, 1, 9, 9);
		Rectangle cpy;
		
		try
		{
			cpy=(Rectangle)org.clone();
			org.changePos(2, 2, 7, 7);
			org.showPosition();
			cpy.showPosition();
		}
		catch(CloneNotSupportedException e)
		{
			e.printStackTrace();
		}
	}
}
728x90