equals()メソッドとhashcode()メソッドについて
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()以外にも、至らない点がたくさんあると思うので、その点に関してもコメントいただけたら嬉しいです。
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;
}
}
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(){
//わかりません。
}
}
Author And Source
この問題について(equals()メソッドとhashcode()メソッドについて), 我々は、より多くの情報をここで見つけました https://qiita.com/Ri4telR/items/3c8090fd58a51251d947著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .