简体   繁体   中英

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?

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;    

    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM