LoginSignup
0
0

More than 5 years have passed since last update.

JAVA hashCode()のオーバーライド

Last updated at Posted at 2015-12-08

▪️Test56.java

import java.util.*;

public class Test56 {
    public static void main(String[] args) {
        Set<Hare56> hare = new HashSet<Hare56>();
        Hare56 h1 = new Hare56();
        Hare56 h2 = new Hare56();
        Hare56 h3 = new Hare56();
        h1.name = "野うさぎ";
        h2.name = "野うさぎ2";
        h3.name = "野うさぎ3";
        h1.item = "にんじん";
        h2.item = "にんじん";
        h3.item = "にんじん";
        h1.item2 = "レタス";
        h2.item2 = "レタス";
        h3.item2 = "レタス";
        hare.add(h1);
        hare.add(h2);
        hare.add(h3);
        System.out.println(hare.size());
        hare.remove(h2);
        System.out.println(hare.size());

    }

}

▪️Hare56.java

public class Hare56 {
    public String name;
    public int hp;
    public String item;
    public String item2;

    public boolean equals(Object o) {
        if (this.name == o && this.item == o && this.item2 == o) {
            return true;
        }
        return false;
    }

    public int hashCode() {
        int result = 35;
        result = result * 31 + name.hashCode();
        result = result * 31 + item.hashCode();
        result = result * 31 + item2.hashCode();
        return result;
    }

}

▪️Test56.java 実行結果
3
2

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0