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?
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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With