I'm new to java.
This time I created a class called Information, and in it ** ・ address [String] ** ** ・ phone (phone number) [String] ** I made a field called. In addition, we have prepared getters and setters for each item.
Next, in order to create a contact search function, create a Person class, and in it, ** ・ name [String] ** ** ・ birthday Day [int] ** ** ・ information [Information] ** I made a field called, and set the name, birthday and information by the factor of the constructor, and prepared each getter.
Next, I tried to add the following three methods to the Information class. ** ・ toString () ** ** ・ equals () ** ** ・ hashcode () **
At this time, if the information is correct, it means that the address and the telephone number match. Also, toString () now returns all fields as strings.
toString () and equals () have been completed somehow, relying on the information on the net. However, I'm struggling because I don't understand hashcode ().
The code I have written now is below. I think there are many points that cannot be reached other than hashcode (), so I would be grateful if you could comment on those points as well.
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(){
//I do not know.
}
}
Recommended Posts