Goldman Sachs Interview Question
Software Engineer / DevelopersIf two objects are equal as given by "equals()" then their hash codes should also be same, but if two objects have same hash code they don't necessarily need to be equal.
public class User {
private String firstName;
private String lastName;
public boolean equals(Object obj){
if(obj == null){return false;}
if (obj instanceof User){
User other = (User) obj;
if(this.firstName.equals(other.firstName) && this.lastName.equals(other.lastName)){
return true;
}
}
return false;
}
public int hashCode(){
return (firstName.hashCode() + lastName.hashCode());
}
}
Since the code is in the same class, so you can use that. Only missing thing seems to be null check.
public class FullName {
private String firstname;
private String lastname;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstname == null) ? 0 : firstname.hashCode());
result = prime * result
+ ((lastname == null) ? 0 : lastname.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof FullName)) {
return false;
}
final FullName other = (FullName) obj;
if (firstname == null) {
if (other.firstname != null)
return false;
} else if (!firstname.equals(other.firstname))
return false;
if (lastname == null) {
if (other.lastname != null)
return false;
} else if (!lastname.equals(other.lastname))
return false;
return true;
}
}
public int hashCode() {
- Snehal January 09, 2010int hash = 0;
for (int i = 0; i < length(); ++i) {
hash = 31 * hash + charAt(i);
}
return hash;
}