Gustavo Gustavo - 5 months ago 10x
Java Question

How to personalize equals for a class and test equal values in a set?

I have to overwrite the equals for my train class which has three attributes : number, wagons and type; Two trains are equal only if their numbers are the same. I have to test whether are duplicates in my train SET. How can I do that ?
This is what i've done so far :

public class Train {
private int number;
private String type;
private int wagons;

public int getNumber() {
return number;

public void setNumber(int number) {
this.number = number;

public String getType() {
return type;

public void setType(String type) {
this.type = type;

public int getWagons() {
return wagons;

public void setWagons(int wagons) {
this.wagons = wagons;

public boolean equals(Object obj) {
Train otherTrain = (Train) obj;
boolean equal = false;
if (otherTrain.getNumber() == this.getNumber()) {
equal = true;
return equal;

Trains DAO :

public class TrainsDAO {
private Set<Train> trainSet = new HashSet<Train>();

public Set<Train> pupulateTheSet() {
Random random = new Random();

for (int i = 1; i < 1000; i++) {
Train train = new Train();
return trainSet;

public static void main(String[] args) {
TrainsDAO trainsDAO = new TrainsDAO();
Set<Train> trains = trainsDAO.pupulateTheSet();
for (Train train : trains) {

And the tests:

public class TrainTest extends TestCase {

private TrainsDAO trainsDAO = new TrainsDAO();
private Set<Train> trainSet = trainsDAO.pupulateTheSet();
public TrainTest(String name) {

protected void setUp() throws Exception {

public void testIfThereAreEqualValuesInSet() {

private boolean duplicateFound() {
//check if there are duplicates in the set return true if there are no false otherwise
return false;


Your equals override as implemented right now may throw:

  • NullPointerException if the argument is null
  • ClassCastException as there's no instanceof check before casting the Object argument to Train

You may want to fix that.

More importantly for hash-based collections, you need to @Override the Object#hashCode method consistently with equals (that is, by returning a hash code based on your train number).

Overriding hashCode correctly will ensure your Trains will be put in different hash buckets if their numbers are different.

Also note: it seems pointless to have unit tests checking for duplicate values in a Set - the whole point of a Set is that it does not allow duplicates.

Docs here.