In: Computer Science
JAVA
Implement a public class method named comparison on a public class Compare that accepts two Object arguments.
It should return 0 if both references are equal.
1 if both objects are equal.
and -1 otherwise.
(SUPER IMPORTANT) Either reference can be null, so you'll need to handle those cases carefully!
Here is what I have so far:
public class Compare {
public static int comparison(Object a, Object b) {
if (a == null || b == null) {
return null;
} else if (a.equals(b)) {
return 0;
} else if (a == b) {
return 1;
} else {
return -1;
}
}
}
I think I'm off with the null part. Thanks!
I have made few changes to your method. I have also added test code. Please use the following
public class Compare {
public static int comparison(Object a, Object b)
{
if (a == null || b == null) {
return -1;
}
// 0 if both references are
equal.
if (a == b) {
return 0;
}
// 1 if both objects are
equal.
if (a.equals(b)) {
return 1;
}
// -1 otherwise
return -1;
}
public static void main(String[] args) {
String s1 = new
String("abcd");
String s2 = s1;
String s3 = new
String("abcd");
String s4 = new
String("abcde");
System.out.println("s1 == s2 : " +
comparison(s1,s2));
System.out.println("s1 == s3 : " +
comparison(s1,s3));
System.out.println("s2 == s3 : " +
comparison(s2,s3));
System.out.println("s1 == s4 : " +
comparison(s1,s4));
}
}
It will produce the following output