Removed
Removed

Reputation: 109

Java: compare two object lists

I'm trying to compare two lists of same objects, those two lists are nodes_cc and nodes_volume. They contains several Node objects. A Node is defined by ID and VALUE. The nodes on the two lists can have common IDs but not common values.

I want to compare the lists like this: I control the first list list (nodes_cc) , if I meet a node that doesn't appear on the second list (nodes_volume), the control MUST stop, even if I will find other nodes that belong even to the second list. I was thinking to use a break so I tried this:

 int count=0;

for (int i=0;i<cc_nodes.size();i++){
    Node node = cc_nodes.get(i);
    for(int j=0;j<volume_nodes.size();j++){       
      Node node2 = volume_nodes.get(j);
        if (node.id==node2.id){
            count++;                      
        }
        else {
            break;         
        }       
    } 
}

The problem is: the for cycle breaks only after the first check (count is 1), where i'm doing wrong? Can you help fix me this?

Upvotes: 0

Views: 187

Answers (2)

alias_boubou
alias_boubou

Reputation: 206

You can Override .equals() and .hashcode() method in Node object to use id as comparator and then :

int count=0;

for (Node node : cc_nodes){
    if(volume_nodes.contains(node))
      count++;
    else 
      break;
}

You can add this in Node object (if id is int value)

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + id;
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Node other = (Node) obj;
    if (id != other.id)
        return false;
    return true;
}

Upvotes: 0

Arnaud
Arnaud

Reputation: 17534

You could use some boolean, and check it after your inner for loop :

 int count=0;

    for (int i=0;i<cc_nodes.size();i++){

        Node node = cc_nodes.get(i);
        boolean found = false;

        for(int j=0;j<volume_nodes.size();j++){       
          Node node2 = volume_nodes.get(j);
            if (node.id==node2.id){
                count++; 
                found = true;           
            }

        } 

        if(!found)
          break;    

    }

Upvotes: 1

Related Questions