Tuesday 30 August 2011

What it will return ..... ? Just try it.

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")));
}
}

6 comments:

  1. C:\Documents and Settings\srinivasa.g\Desktop\>javac Name.java
    Name.java:15: '(' or '[' expected
    Set s = new HashSet();
    ^
    1 error

    ReplyDelete
  2. My Dear Anonymous call to 3510 and ask him what is the ans

    ReplyDelete
  3. It will complie and execute properly correctly.

    ReplyDelete
  4. Set 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.

    ReplyDelete
  5. All the above are true....!, If u have any doubt ask the coder.

    ReplyDelete
  6. What we need to do, to print true.

    We 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.

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...