SAS Research Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
I have tried hard to figure out answer.. but couldn't find any.. even if override hashcode it will be the same for same object
class EqualsTest{
public boolean equals(EqualsTest a)
{
if (this==a)
{
return true;
}
return false;
}
public static void main(String args[])
{
EqualsTest a =new EqualsTest();
EqualsTest b= new EqualsTest();
System.out.println(a.equals(a));
}
}
This code is not overriding as needed in program, instead is doing overloading
Here is the simple answer:
class TestA {
public boolean equals(Test1 t) {
return false;
}
}
Override the equals method in the new class which always return false.
It could be done with small hack in println of Printstram :)
import java.io.PrintStream;
public class Program {
static {
PrintStream ps = System.out;
System.setOut(new PrintStream(ps){
public void println(boolean x) {
synchronized (this) {
super.println(!x);
}
}
});
}
public static void main(String args[]) {
TestA testObj = new TestA();
System.out.println(testObj.equals(testObj));
}
}
class TestA {
}
Something I have in mind is like this:
public TestA {
private int n;
private Timer time;
public void TestA() {
n = 0;
time += nIncrease();
timer.start();
}
private void nIncrease() {
n = n + 1;
}
}
Unfortunately, overriding hashcode wont help. The default implementation of Object just checks for reference equality and does not consider hashcode while calling the "equals" method. That said, frankly, I am unable to figure out the answer myself.
You can make the constructor do:
System.out.println ("false");
System.exit(0);
Hah, take that, Java!
Class A{
public boolean equals(Object o)
{
A obj=(A)o;
if(this==obj)
return false;
else
return true;
}
public static void main(String...args)
{
TestA testObj = new TestA();
System.out.println(testObj.equals(testObj));
}
}
class B
{
public boolean equals(Object o) // overriding in the superclass
{B obj=(B)o;
if(this.hashCode()==obj.hashCode())
return false;
else
return true;
}
}
class TestA extends B{
public static void main(String...args)
{
TestA testObj = new TestA();
System.out.println(testObj.equals(testObj));
}
}
Here is the trick, overriding equals have the signature which take Object as argument. so without overriding just implement a new method called equals which takes argument of type Test (note that you are not overriding equals from java specification but implementing a new equals )
note override equals has the below signature (see the argument)
- Yogesh Bhardwaj June 08, 2013