Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equals to return false [duplicate]

Tags:

java

Possible Duplicate:
Returning false from Equals methods without Overriding

One of my colleague asked me a question today as mentioned below

Write TestEquals class(custom or user defined class) so that the below s.o.p in the code prints false.

public class Puzzle3 {
  public static void main(String[] args) {
    TestEquals testEquals = new TestEquals();
    System.out.println(testEquals.equals(testEquals));
  }
}

Note: You cannot override equals method.

I thought a lot but couldn't find the solution without overriding equals.Does anybody have any idea how it can be done?

like image 637
Anand Avatar asked Aug 30 '12 18:08

Anand


2 Answers

use

public boolean equals(TestEquals equals) {
    return false
}

To override equals you need the input parameter to be of type object so the above code snippet theorectially is not overriding equals from the object method

like image 196
RNJ Avatar answered Oct 18 '22 09:10

RNJ


EDIT: Apparently someone else arrived at this idea first on another thread, but I'll leave this here since this code is significantly simpler.


class TestEquals {

  static {
    System.setOut(new PrintStream(new FilterOutputStream(System.out) {
      public void write(byte[] buf, int pos, int len) throws IOException {
        if (len >= 4 && buf[pos] == 't') {
          out.write(new byte[] {
              (byte) 'f', (byte) 'a', (byte) 'l', (byte) 's', (byte) 'e'
            });
          out.write(buf, pos + 4, len - 4);
        } else {
          out.write(buf, pos, len);
        }
      }
    }));
  }
}

This horrible hack does not override or overload anything to do with equals, but the act of creating an instance of TestEquals causes the class to load which wraps System.out so that any subsequent print that starts with 't' will cause "false" to be printed instead of the first 4 bytes. (Assuming the default encoding is not something super-exotic.)

like image 29
Mike Samuel Avatar answered Oct 18 '22 10:10

Mike Samuel