I have a serializable class, that I'd like to compare. It contains many fields and will probably change many times in the future. What are the downsides of implementing equals like this:
public class ProbierKlasse implements Serializable{
private static final long serialVersionUID = -7996094306948821373L;
private File dir = new File("dir");
private File subDir = new File(dir, "subDir");
private File file = new File(dir, "file");
public static void main(String[] args) throws IOException {
ProbierKlasse pk = new ProbierKlasse();
ProbierKlasse pk1 = new ProbierKlasse();
System.out.println(pk.equals(pk1)); //prints true
pk1.subDir = new File(pk1.dir, "anotherDir");
System.out.println(pk.equals(pk1)); //prints false
}
@Override
public boolean equals(Object obj) {
byte[] thisBytes = getByteArray(this);
byte[] objBytes = getByteArray((ProbierKlasse)obj);
return Arrays.equals(thisBytes, objBytes);
}
private byte[] getByteArray(Serializable obj){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
} catch (IOException e) {
throw new RuntimeException(e);
}
return baos.toByteArray();
}
}
I could think of performance as an issue, but in this case it is not so important. It has the big advantage, that I don't have to adjust it, if I add new fields.
Thanks in advance and please don't hate me for asking.