代码之家  ›  专栏  ›  技术社区  ›  AlikElzin-kilaka planben

在Java中,是否有一个具有“BuffjQueal.DRAITO”功能的哈希集?

  •  1
  • AlikElzin-kilaka planben  · 技术社区  · 7 年前

    我想复制 HashSet 同时不阻止新插入。

    BlockingQueue drainTo 方法。

    如何使用 哈希表 ?谢谢。

    *我愿意使用“并发哈希集”结构,比如 ConcurrentHashMap.newKeySet() .

    1 回复  |  直到 7 年前
        1
  •  1
  •   xtratic Rob    7 年前

    像这样的方法怎么样:

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