【问题标题】:Synced TreeSet Cast?同步树集演员?
【发布时间】:2016-01-24 19:42:42
【问题描述】:

我在 Java 中使用 TreeSet 来保存整数列表:

TreeSet<Integer> num = new TreeSet<Integer>();

由于我的应用程序有多个线程,我希望能够同步地访问它。我正在使用Collections.synchronizedSortedSet(num);,这会返回一个Collections$SortedSet。我的问题是这不能转换为TreeSet - 它只能转换为SortedSet。我无法更改 num 对象的类,因此它必须转换为 TreeSet

有谁知道我如何将Collections$SortedSet 转换为TreeSet,或者我可以通过其他方法来同步这个TreeSet

【问题讨论】:

    标签: java collections synchronization treeset


    【解决方案1】:

    没有这样的实现,但您可以轻松实现。只需扩展TreeSet,并用同步方法覆盖它的方法。

    例如:

    public class MySyncedTreeSet extends TreeSet {
        @Override
        public synchronized boolean isEmpty() {
            return super.isEmpty();
        }
    
        @Override
        public synchronized boolean contains(Object o) {
            return super.contains(o);
        }
    
        // and the same for all other methods
    }
    

    【讨论】:

    • 我想我最终不得不这样做......不过谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 2015-09-25
    • 1970-01-01
    • 2015-09-08
    • 2021-01-29
    • 1970-01-01
    • 2018-01-03
    相关资源
    最近更新 更多