Mike
Mike

Reputation: 79

Why does the contains() method in Java not work as expected?

I am writing a method that creates an ArrayList S_Comp that contains all elements which are included in the array allNodes, but which are not included in the ArrayList solution (whose elements are all included in allNodes). When I print solution and allNodes, I can easily see that S_Comp should be containing 7 elements. However, all elements from allNodes are added to S_Comp, also the elements which are included in nodesS. What could be the problem here?

Below you can find my code for the method. Before calling this method, S_Comp has only been initialized as new ArrayList<MyNodesData>, so its size is 0.

public void generateSComp(DataFile testDataFile, ArrayList<Route> solution, ArrayList<MyNodesData> S_Comp)
    {
        System.out.println("solution: " + solution.toString());
        ArrayList<MyNodesData> nodesS = getNodesS(solution);
        System.out.println("NodesS: " + nodesS.toString());
        System.out.println("Size nodesS: " + nodesS.size());
        MyNodesData[] allNodes = testDataFile.getNodes();
        System.out.println("allNodes: " + Arrays.toString(allNodes));
        for(MyNodesData node : allNodes)
        {
            if(!nodesS.contains(node))
            {
                System.out.println(node.toShortString() + " is not in nodesS");
                S_Comp.add(node);
            }
        }

Upvotes: 2

Views: 2044

Answers (3)

Shubham Kadlag
Shubham Kadlag

Reputation: 2318

Refer here for the contains method of ArrayList javadoc here: https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#contains-java.lang.Object-

It says

public boolean contains(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

So it will work only if you override equals method of Object Class as you want in MyNodesData class. Moreover as you may already be knowing the contract between equals() and hashcode() method, it is highly recommended to override hashcode() along with equals().

For more information : Why do I need to override the equals and hashCode methods in Java?

Upvotes: 2

A. Llorente
A. Llorente

Reputation: 1162

contains works just as expected, it will check if the object you pass equals the object in the list. So if you are not getting the expected behavior is because those objects do not equal.

You will have to debug that code to check why the equals is not returning what you expect.

Edit: I read that you are not overriding equals and hashcode in MyNodesData class, so you should do it as other people suggest

Upvotes: 0

vishal ms
vishal ms

Reputation: 44

override hashcode and equals method in MyNodesData class and then check.

Upvotes: 0

Related Questions