从java

时间:2016-01-11 11:10:33

标签: java hashset

编写代码时遇到问题。我在java中使用HashSet 我要求如果hashset中不存在对象,则使用add()方法添加该特定对象。

但是如果对象已经存在,我需要将该特定对象保存到其他地方。但是我没有在java中看到hashset的get()方法。有人可以帮忙吗?

有没有办法从HashSet中获取对象,或者请建议一些其他数据结构。

3 个答案:

答案 0 :(得分:0)

检查对象是否已存在于集合中您可以使用接口Collection的方法contains

或者只是add它并检查add的返回值。 (有关详细信息,请参阅add文档)

if (set.add(myObject)) {
    // Added
} else {
    // Not added because it was already present
}

答案 1 :(得分:0)

您可以使用HashMap<YourClass,YourClass>

YourClass yourClassKey = ...;
YourClass obj = map.get(yourClassKey); // if a key equal to yourClassKey is in the map,
                                       // you get the existing object from the map 
if (obj == null) { // if yourClassKey is not in the map, you add it
    map.put(yourClassKey,yourClassKey);
    obj = yourClassKey;
}

顺便说一句,使用HashMap代替HashSet不会需要更多内存,因为HashSet无论如何都会在内部使用HashMap

答案 2 :(得分:0)

检索HashSet中包含的对象的示例可能是

decltype(std::endl<char, std::char_traits<char>>)

输出XXX