Hi, I have the program, which is a traffic simulation, and I have a few linked lists in it. I'd like to ask you what is the easiest way to check if I don't have duplicats in them? The code which runs it looks like that:

    public static void main(String[] args) {
        Simulation s = new Simulation();

        s.addRoad(Road.Orientation.HORIZONTAL, 50, 5,3);
        s.addRoad(Road.Orientation.HORIZONTAL, 500,1,4);
        s.addRoad(Road.Orientation.VERTICAL, 100,3,2);
        s.addRoad(Road.Orientation.VERTICAL, 600,2,3);
        s.addRoad(Direction.DOWN, 1,300, 2,3);
        s.addRoad(Direction.RIGHT, 3 ,340,1,2);
        s.addRoad(Direction.UP,0,500,2,1);
        s.addRoad(Direction.LEFT,2, 400,1,2);
        s.addIntersection(0,2);
        s.addIntersection(3,0);
        s.addIntersection(2,1);
        s.addIntersection(1,3);

        s.start();
    }

Simulation extenst Thread, so first I build road system, then add intersection (if there is a T shape intersection between roads, the intersection is being created automatically, if it is + shape, I can add it or not), and I thought I would have to run something like that in @Before function for few seconds, and then run tests on LinekdLists - but how to do it to work?. And secondly is that a good idea to make a @Test function and do through LinkedList with Iterator checking with assertSame if two elements are the same object?

The simplest code to check for duplicates in a List is probably to add its items to a HashSet (HashSet does not allow duplicates) and check if the size is the same, eg

        var x = new ArrayList<Integer>();
        x.add(1); x.add(2); x.add(2); x.add(3);

        var y = new HashSet<Integer>(x);
        System.out.println(x.size() - y.size() + " duplicates");

        // you can code that as a simple assertion...

        assert x.size() == new HashSet<Integer>(x).size();

... or you could add them one at a time because the add method returns false if the item has already been added (ie is a duplicate)

Either way yu will need to have suitable equals methods in your Road and Intersection classes

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.