我在Java中使用TreeSet来保存整数列表:
TreeSet<Integer> num = new TreeSet<Integer>();
因为我的应用程序有多个线程,所以我希望能够同步访问它。我使用的是Collections.synchronizedSortedSet(num);,这将返回一个Collections$SortedSet。我的问题是,这不能被转换到一个TreeSet-它只能被转换到一个SortedSet。我无法更改num对象的类,因此必须将其转换为TreeSet。
有人知道我可能如何将Collections$SortedSet转换为TreeSet,或者其他方法来同步这个TreeSet吗?
发布于 2016-01-24 19:52:45
没有这样的实现,但您可以轻松地打开一个。只需扩展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
}https://stackoverflow.com/questions/34980565
复制相似问题