jeudi 5 mai 2016

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;
    }

    @Override
    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();
            train.setNumber(random.nextInt(10));
            train.setWagons(random.nextInt(30));
            train.setType("Inter-city");
            trainSet.add(train);
        }
        return trainSet;
    }

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

And the tests:

public class TrainTest extends TestCase {

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

    @Override
    protected void setUp() throws Exception {
        super.setUp();
    }

    @Test
    public void testIfThereAreEqualValuesInSet() {
        assertTrue(!duplicateFound());
    }

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

Aucun commentaire:

Enregistrer un commentaire