Thursday, May 16, 2013

Using Eclipse to generate hashCode() and equals()

Right-click at the selected file, choose Source-> generate hashCode() and equals()
Then you can choose which attributes uniquely identify the object and then Eclipse generates hashCode() and equals() implementation like this:

/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((code == null) ? 0 : code.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof OtherObject))
return false;
OtherObject other = (OtherObject) obj;
if (code == null) {
if (other.code != null)
return false;
} else if (!code.equals(other.code))
return false;
return true;
}

Sonar: Correctness - Impossible downcast of toArray() result

When we are facing with the Sonar message "Correctness - Impossible downcast of toArray() result" what does this mean?

This message appears when we have something like this:

String[] getAsArray(Collection c) {
  return (String[]) c.toArray();
}


This will usually fail by throwing a ClassCastException.
The correct way to get an array of a specific type from a collection is by the usage of

c.toArray(new String[c.size()]);


that will return a String[], for this scenario.