EqualsHaschcodTest

조수경·2021년 11월 2일
0

고급자바

목록 보기
10/97

equals()메서드 ==> 두 객체의 내용이 같은지 검사하는 연산

hashCode()메서드 => 두 객체의 동일성을 검사하는 연산자

  • HashSet, Hashtable, HashMap과 같이 Hash로 시작하는 컬랙션 객체들은
    객체의 의미상의 동일성을 비교하기 위해 hashCode()메서드를 호출하여 비교한다.
    그러므로, 객체가 같은지 여부를 결정하려면 hashCode()메서드를 재정의 해야 한다.
    (hashCode()까지 일치해야 완전히 일치하는 데이터로 보는 것)
  • hashCode()메서드에서 사용하는 '해싱 알고리즘'은 서로 다른 객체들에 대해서 같은 hashCode가 발생할 수 있다.
package kr.or.ddit.basic;

import java.util.HashSet;

public class EqualsHaschcodTest {

       public static void main(String[] args) {
       Person p1 = new Person();
       p1.setId(1);
       p1.setName("홍길동");
       
       Person p2 = new Person();//객체 생성
       /*p2.setId(2);
       p2.setName("일지매");*///값이 다르면 2개가 결과로 나옴
       p2.setId(1);
       p2.setName("홍길동");//값이 같으면 1개가 결과로 나옴
       
       Person p3 = p1;//서로 참조값이 같다는 소리 = > 해쉬코드가 같을 수 밖에 없음
       
       System.out.println(p1 == p2);//갖고있는 값(참조 값)이 같은지 물어보는 것 -> false
       System.out.println(p1.equals(p2));//참조값이 달라서 false 
       
       /*  equals가 없는데도 실행되는 이유는? object에 만들어져 있어서
        * public boolean equals(Object obj){
        * return this == obj;
        * }
        */
       
       //오버라이딩: 자식객체에서 조상 객체를 새롭게 조정하는 것 
       //-> String객체가 그러함 
       
      /* String str1 = "이순신";
       String str2 = "이순신";// 위와 같은 문자열
       String str3 = new String("이순신");//다른 공간에 문자열이 생김
       String str4 = new String("이순신");*/
       
       HashSet<Person> testSet = new HashSet<>();
       
       testSet.add(p1);
       testSet.add(p2);
       
       System.out.println("set의 크기: "+ testSet.size());
       System.out.println("p1 : "+ p1.hashCode());
       System.out.println("p2 : "+ p2.hashCode());
       System.out.println("p3 : "+ p3.hashCode());
       //해시 코드를 같게 만드는 것은 어려움 , 되도록이면 안나오게 해야됨
       
       
	}

}


class Person{
	private int id;
	private String name;

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
          
		Person other = (Person) obj;
		if (id != other.id)
			return false;
		if (name == null) {//이름이 널일때
			if (other.name != null)//다른이름이 널이아니면
				return false;
		} else if (!name.equals(other.name))//다른 이름과 같지 않으면
			return false;
		return true;
	}
	
	//객체의 id값과 name값이 같으면 true를 반환하도록 개정의한다.
	/*@Override
	public boolean equals(Object obj) {
                //equals는 아무객체와 비교가능해서 Object
		if(obj == null) return false;
		
		//같은 유형의 클래스인지 검사
		if(this.getClass() != obj.getClass()) return false;
                //클래스 유형 알아내기
		
		//참조값이 같은지 검사
		if(this == obj) return true;
		
		//매개변수에 저장된 객체를 현재 객체 유형으로 형변환 한다.
		Person that = (Person)obj;
		
		if(this.name == null && that.name != null)
			return false;
		
		if(this.id == that.id && this.name == that.name)
			return true;
		
		if(this.id == that.id && this.name.equals(that.name))
			return true;
		
	    return false;
	    
	}*/
	
	
	
}
profile
신입 개발자 입니다!!!

0개의 댓글

Powered by GraphCDN, the GraphQL CDN