列表中的重复对象

时间:2013-04-02 12:20:42

标签: networking duplicates nodes rssi xbee

我正在编写一个编程项目,我想将一些对象存储在列表中,但是我无法摆脱重复项。

这是我的对象

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

代码在线程内部,因此代码循环。

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 个答案:

答案 0 :(得分:0)

如果不了解系统的其余部分以帮助确定为什么handleAtCommandResponse使用相同的响应多次调用,请注意您可以使用Set实施,而不是HashSet列表以防止存储重复的对象。如果尚未实现hashCode(),则可能需要NodeDiscover来实现。{/ p>

Set不允许重复的对象。如果使用相同的对象(而不是put()等于集合中另一个对象的对象)调用hashCode()两次,则第一个实例将替换为第二个实例。