import java.util.*;
public class Name {
private final String first, last;
public Name(String first, String last) {
this.first = first;
this.last = last;
}
public boolean equals(Object o) {
if (!(o instanceof Name))
return false;
Name n = (Name)o;
return n.first.equals(first) && n.last.equals(last);
}
public static void main(String[] args) {
Set<Name> s = new HashSet<Name>();
s.add(new Name("Mickey", "Mouse"));
System.out.println(s.contains(new Name("Mickey", "Mouse")));
}
}
public class Name {
private final String first, last;
public Name(String first, String last) {
this.first = first;
this.last = last;
}
public boolean equals(Object o) {
if (!(o instanceof Name))
return false;
Name n = (Name)o;
return n.first.equals(first) && n.last.equals(last);
}
public static void main(String[] args) {
Set<Name> s = new HashSet<Name>();
s.add(new Name("Mickey", "Mouse"));
System.out.println(s.contains(new Name("Mickey", "Mouse")));
}
}
C:\Documents and Settings\srinivasa.g\Desktop\>javac Name.java
ReplyDeleteName.java:15: '(' or '[' expected
Set s = new HashSet();
^
1 error
My Dear Anonymous call to 3510 and ask him what is the ans
ReplyDeleteIt will complie and execute properly correctly.
ReplyDeleteSet eliminates duplicates by using equals() and hashCode() methods, the o/p is false because Your Class Name doesn't implement bothe equals() and hashCode() methods.
ReplyDeleteAll the above are true....!, If u have any doubt ask the coder.
ReplyDeleteWhat we need to do, to print true.
ReplyDeleteWe need to override the hashcode() method.
Code :
public int hashCode() {
return 37 * first.hashCode() + last.hashCode();
}
Larning : In summary, always override hashCode when you override equals. More generally,
obey the general contract when you override a method that has one. This is
an issue for most of the non-final methods declared in Object class.