code_junkie

When overriding equals in Java, why does it not work to use a parameter other than Object?

Nov 12th, 2011
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. public class MyClass {
  2. private int x;
  3. public MyClass(int n) { x = n; }
  4. public boolean equals(Object o) { return false; }
  5. public boolean equals(MyClass mc) { return x == mc.x; }
  6. public static void main(String[] args) {
  7. List<MyClass> list = new ArrayList<MyClass>();
  8. list.add(new MyClass(3));
  9. System.out.println("Contains 3? " + list.contains(new MyClass(3)));
  10. }
  11. }
  12.  
  13. public boolean equals(Object o) {
  14. if(!(o instanceof MyClass))
  15. return false;
  16. MyClass mc = (MyClass)o;
  17. return x == mc.x;
  18. }
  19.  
  20. boolean contains(Object o)
  21. Returns true if this list contains the specified element.
  22.  
  23. boolean contains(E o)
  24. Returns true if this list contains the specified element.
  25.  
  26. private transient Object elementData[];
  27.  
  28. public boolean contains(Object elem) {
  29. return indexOf(elem) >= 0;
  30. }
  31.  
  32. public int indexOf(Object elem) {
  33. if (elem == null) {
  34. for (int i = 0; i < size; i++)
  35. if (elementData[i]==null)
  36. return i;
  37. } else {
  38. for (int i = 0; i < size; i++)
  39. if (elem.equals(elementData[i]))
  40. return i;
  41. }
  42. return -1;
  43. }
  44.  
  45. class A{
  46. public int content;
  47. A(){
  48. this(0);
  49. }
  50. A(int value){
  51. content = value;
  52. }
  53. public boolean equals(Object obj){
  54. System.out.println("overriding equals method");
  55. return this.content == ((A) obj).content;
  56. }
  57. public boolean equals(A a){
  58. System.out.println("overloading equals method");
  59. return this.content == a.content;
  60. }
  61. public static void main(String[] args){
  62. A x = new A(1);
  63. A y = new A(2);
  64. Object z = new A(1);
  65. System.out.println(x.equals(y));
  66. System.out.println(x.equals(x));
  67. System.out.println(x.equals(z));
  68. //override as z is declared as Object at compile time
  69. //so it will use methods in class Object instead of class A
  70. System.out.println(x.equals((Object) y));
  71. System.out.println(x.equals((Object) x));
  72. }
  73. }
  74. //rant: they didn't teach me these in javaschool and I had to learn it the hard way.
Add Comment
Please, Sign In to add comment