0

Im working on a programming project, I want to store some objects in a list but, but I cant get rid of the duplicates.

This is my object

nd = nodeAddress16=0x10,0x03, nodeAddress64=0x00,0x13,0xa2,0x00,0x40,0x6f,0x8d,0xfc, rssi=-47, nodeIdentifier= [0x10,0x03]

The code is inside a thread, so the code is looping.

private void handleAtCommandResponse(XBeeResponse response) {
    //TODO Implement your code here, to handle particular AT command responses, if desired.
    System.out.println("NetworkNode: Received AT Response:"+((AtCommandResponse)response).getCommand());

    if (response.getApiId() == ApiId.AT_RESPONSE) {
        NodeDiscover nd = NodeDiscover.parse((AtCommandResponse)response);
        System.out.println("Node discover response is: " + nd);

        nodeDiscoverList.add(nd); //add to list, but gives duplicates of nd.

        //add to list if not already in it
        //if already in list replace that object with the new object
        //duplicate objects are not allowed ==> only one object in the list can contain a specific address.
        // Only addresses are static values, other values may change over time.


        }
    else {
        log.debug("Ignoring unexpected response: " + response); 
    }
}

1 Answers1

0

Without understanding the rest of the system to help determine why handleAtCommandResponse is being invoked multiple times with the same response, note that you can use a Set implementation like HashSet instead of a List to keep from storing duplicate objects. You may need NodeDiscover to implement hashCode() if it does not already.

A Setdoes not allow duplicate objects. If you call put() with the same object (rather, an object whose hashCode() is equal to that of another object in the set) twice, the first instance is replaced by the second.

spork
  • 1,185
  • 1
  • 11
  • 17