我想要一种将HashSet的内容复制到集合中而不阻止新插入的方法。

BlockingQueuedrainTo方法中具有此功能。

HashSet怎么做?谢谢。

*我愿意使用ConcurrentHashMap.newKeySet()之类的“并发HashSet”结构。

最佳答案

这样的方法怎么样:

public <T> int drainTo(Set<? extends T> source, Collection<T> target) {
    Iterator<? extends T> it = source.iterator();
    int count = 0;
    while (it.hasNext()) {
        target.add(it.next());
        it.remove();
        count++;
    }
    return count;
}

public static void main(String[] args) throws Exception {
    Collection<String> list = new ArrayList<>();

    // HashSet<String> set = new HashSet<>();
    Set<String> set = ConcurrentHashMap.newKeySet();
    set.add("1");
    set.add("2");
    set.add("3");

    new Thread(() -> {
        set.add("4");
        set.add("5");
    }).start();

    drainTo(set, list);

    // could print [1, 2, 3] , [1, 2, 3, 4], or [1, 2, 3, 4, 5]
    // since there's no guarantee that the thread finished putting all elements in yet
    System.out.println(list);
}

10-08 01:18