Sunday, August 16, 2009

Puzzle 47 - Solution

There are different categories of solutions to this puzzle, with the most simplest placed first to the most difficult!

1. DataType1 - Datatype4 all have different values and we rely on autoboxing and numeric promotions to get the job done.

package com.twister;
public class Mystery {

public static boolean isEqual(Integer f1,Long f2){
return f1.equals(f2);
}

public static void main(String[] args) {
int f1 = 1;
long f2 = 1;

System.out.println(
"f1 is equals to f2 : "+ (f1==f2));//prints true
System.out.println("f1 is equals to

f2 :
"+ isEqual(f1,f2));//prints false
}

}


2. DataType1 - Datatype2 are same and Datatype3 - Datatype4 are the same. Relies on autoboxing and the fact that the equals method of Float treats +0 as not equal to -0.

package com.twister;
public class Mystery {

public static boolean isEqual(Float f1, Float f2){
return f1.equals(f2);
}

public static void main(String[] args) {
float f1 = +0.0f;
float f2 = -0.0f;

System.out.println(
"f1 is equals to f2 : "+ (f1==f2));//prints true
System.out.println("f1 is equals to

f2 :
"+ isEqual(f1,f2));//prints false
}

}


3. DataType1 - Datatype4 are all the same.

package com.twister;
public class Mystery {

public static boolean isEqual(Object f1, Object f2){
return f1.equals(f2);
}

public static void main(String[] args) {
Object f1
= new Object()
{
@Override
public boolean equals(Object obj) {
return false;
}
};
Object f2
= f1;

System.out.println(
"f1 is equals to f2 : "+ (f1==f2));//prints true
System.out.println("f1 is equals to

f2 :
"+ isEqual(f1,f2));//prints false
}
}

No comments:

Post a Comment

Solution for this question?