Re: equality and null pointers
On Apr 11, 11:45 am, "visionset" <s...@ntlworld.com> wrote:
<julien.robins...@gmail.com> wrote in message
news:1176304398.560236.38520@q75g2000hsh.googlegroups.com...
Hi all, a code factorization question...
the following expression:
a.equals(b)
returns a boolean, even if 'b' is null (in which case it's obviously
false, because otherwise there would be a NullPointerException).
Well here lies your problem.
Personally I'd say it was more likely that
null != null
Just like in SQL.
So this underlines the fact that only you, your design in your application
can determine what equality is.
For the same reason you override equals() to put your spin on equality so
you must determine if null == null, nul!=null or indeed what
myObj.equals(null) should evaluate to.
This is great for tests such as:
"blob".equals(myPersonalString)
What if both a and b can be null? I end up writing the same code again
and again... calling for factorization.
This is the factorized code:
public class Utils {
public static boolean areEqual(Object obj1, Object obj2) {
return (obj1 == null) ? (obj2 == null) : (obj1.equals(obj2));
}
}
Questions are:
- does this already exist somewhere in Java, and I have overlooked it
(buried somewhere in with other utility methods)?
- if not, does anybody prefer some other code than what I suggested?
--
Mike W- Hide quoted text -
- Show quoted text -
Here is some code showing equals and hascode that you can implement in
your calsses.
public class Worker {
private String name;
private double salaryRate;
public Worker (String name, double rate) {
this.name = name;
this.salaryRate = rate;
}
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((name == null) ? 0 :
name.hashCode());
long temp;
temp = Double.doubleToLongBits(salaryRate);
result = PRIME * result + (int) (temp ^ (temp >>> 32));
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Worker other = (Worker) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(salaryRate) !=
Double.doubleToLongBits(other.salaryRate))
return false;
return true;
}
}
Dinesh