Your equals()
and hashCode()
methods are wrong. You are breaking the contract.
If I understood well you want to find the index of e
although there is only c
in the list, and you want to do so abusing the String#equals()
checking equality only for the first 5 letters. So c.code = 1-202
, e.code = 1-202.0
, doing c.code.equals(e.code.subString(0, e.code.lenght()-2))
should hold true
.
This is the correct implementation:
public class OPCode {
public String code;
public OPCode(String code){
this.code = code;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((code == null) ? 0 : code.split("\\.")[0].hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OPCode other = (OPCode) obj;
if (code == null) {
if (other.code != null)
return false;
} else{
String thisCode = code.split("\\.")[0];
String otherCode = other.code.split("\\.")[0];
if (!thisCode.equals(otherCode))
return false;
}
return true;
}
}
Note that I used the method String#split
since (and this is my assumption) you want to be equal codes with same numerical part without considering decimal part. Using split
we avoid managing variable number of literals.
Test it with:
ArrayList<OPCode> t_codes = new ArrayList<OPCode>();
OPCode c = new OPCode("1-202");
t_codes.add(c);
OPCode e = new OPCode("1-202.0");
System.out.println(t_codes.indexOf(e)); // -1 <-- Problem here now gives 0
System.out.println(t_codes.indexOf(c));
BTW I created both method using eclipse built in function via Source>Generate hashCode() and equals()… and modified for the task.