Javaでイコールを書き換えるときにハッシュコードを書き換える必要がある理由-例

エンティティークラス

クラスPoint {
     private  int x;
    プライベート 整数y; 

    public  int getX(){
         xを返す; 
    } 

    public  void setX(int x){
         this .x = x; 
    } 

    public  int getY(){
         yを返す; 
    } 

    public  void setY(int y){
         this .y = y; 
    } 

    @Override 
    public  boolean equals(Object obj){
         ifthis == obj)// ref相等
        {
             return  true ; 
        } 
        if(obj == null || this .getClass()!= obj.getClass()){
             return  false ; 
        } 
        Point that = (Point)obj;
        戻り X == that.x && Y == that.y。// 対比值
    } 
}

上記のコードは、equalsを書き換えます。

比較する

@ Slf4j
 public  class EqualsHashDemo { 


    public  static  void compare(){ 
        Point a = new Point(); 
        a.setX( 1 ); 
        a.setY( 2 ); 

        ポイントb = new Point(); 
        b.setX( 1 ); 
        b.setY( 2 ); 

        log.info( "a.equals(b)is" + a.equals(b)); 

    } 
}

今回は出力は真です

比較のためにオブジェクトをハッシュセットにロードする

@ Slf4j
 public  class EqualsHashDemo { 


    public  static  void compare(){ 
        Point a = new Point(); 
        a.setX( 1 ); 
        a.setY( 2 ); 

        ポイントb = new Point(); 
        b.setX( 1 ); 
        b.setY( 2 ); 

        log.info( "a.equals(b)is" + a.equals(b)); 

        HashSet <Point> points = new HashSet <> (); 
        points.add(a); 

        log.info("points.contains(b)is" + points.contains(b)); 

    } 
}

アウトプット

a.equals(b)はtrue 
 points.contains(b)はfalse

これは、ハッシュコードが書き換えられなかったためです。書き換えなし。デフォルトでは、親クラスのハッシュコードを使用します。各オブジェクトは異なります(ハッシュセットの実装については、当面は説明しません)

ハッシュコードを書き換える

クラスPoint {
     private  int x;
    プライベート 整数y; 

    public  int getX(){
         xを返す; 
    } 

    public  void setX(int x){
         this .x = x; 
    } 

    public  int getY(){
         yを返す; 
    } 

    public  void setY(int y){
         this .y = y; 
    } 

    @Override 
    public  boolean equals(Object obj){
         ifthis == obj)// ref相等
        {
             return  true ; 
        } 
        if(obj == null || this .getClass()!= obj.getClass()){
             return  false ; 
        } 
        Point that = (Point)obj;
        戻り X == that.x && Y == that.y。// 対比值
    } 

    @Override 
    public  int hashCode(){
         return Objects.hash(x、y); 
    } 
}

もう一度走る

a.equals(b)はtrue 
 points.contains(b)はtrue

同様に、ハッシュコードを書き換えた後、次のコードでも通常の値0000を出力できます

  HashMap <Point、String> map = new HashMap <> (); 
        map.put(a、 "00000" ); 
        log.info(map.get(b));

繰り返されない場合はnullを出力します

 

おすすめ

転載: www.cnblogs.com/Brake/p/12716839.html