0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

equals()メソッドとhashcode()メソッドについて

Posted at

java初心者です。

今回Informationというクラスを作り、その中に
・address(住所)[String]
・phone(電話番号)[String]
というフィールドを作りました。
また、それぞれの項目にgetter及びsetterを用意しました。

次に、連絡先の検索機能を作るために、Personクラスを作り、その中に、
・name(名前)[String]
・birthDay(誕生日)[int]
・information(情報)[Information]
というフィールドを作り、コンストラクタの因数で名前と誕生日と情報をセットするようにして、それぞれのgetterを用意しました。

次に、Informationクラスに以下の3つのメソッドを追加しようとしました。
・toString()
・equals()
・hashcode()

このときInformationが正しいというのは、住所と電話番号が一致していることとしました。
また、toString()では、すべてのフィールドを文字列にして返すようにしました。

toString()、equals()はネットの情報などを頼りに、なんとなくですが完成させました。
しかし、hashcode()がいまいちよくわからず、苦戦しています。

現在私が作成したコードは以下のものとなっています。
hashcode()以外にも、至らない点がたくさんあると思うので、その点に関してもコメントいただけたら嬉しいです。

Person.class

public class Person {

  private String name;
  private int birthday;
  private Information information;

  public Person(String name, int birthday, Information information) {
    this.name = name;
    this.birthday = birthday;
    this.information = information;
  }

  public String getName() {
    return this.name;
  }

  public int getBirthday() {
    return this.birthday;
  }

  public Information getInformation() {
    return this.information;
  }
}
Information.class

public class Information {

  private String address;
  private String phone;

  public Information() {}

  public String getAddress() {
    return this.address;
  }

  public String getPhone() {
    return this.phone;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  public void setPhone(String phone) {
    this.phone = phone;
  }

	public String toString(){
    String str = address+","+phone;
    return str;
  }
  
  public boolean equals(Object other) {
    
     if (this == other) { 
            return true;
        }

     if (!(other instanceof Information)) { 
            return false;               // 
        }

        Information otherInformation = (Information) other;
     if ((this.address == otherInformation.getAddress()) && (this.phone == otherInformation.getPhone())){ 
            return true;
        }
        return false;
    }
  
	public int hashcode(){
   //わかりません
  }

}
0
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?