同步 TreeSet 演员表?
Synced TreeSet Cast?
我在 Java 中使用 TreeSet 来保存整数列表:
TreeSet<Integer> num = new TreeSet<Integer>();
由于我的应用程序有多个线程,我希望能够同步访问它。我正在使用 Collections.synchronizedSortedSet(num);
而这个 returns 和 Collections$SortedSet
。我的问题是这不能转换为 TreeSet
- 它只能转换为 SortedSet
。我无法更改 num 对象的 class,因此它 必须 转换为 TreeSet
.
有谁知道我如何将 Collections$SortedSet
转换为 TreeSet
,或者我可以用来同步此 TreeSet
的其他方法?
没有这样的实现,但您可以轻松实现。只需扩展 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
}
我在 Java 中使用 TreeSet 来保存整数列表:
TreeSet<Integer> num = new TreeSet<Integer>();
由于我的应用程序有多个线程,我希望能够同步访问它。我正在使用 Collections.synchronizedSortedSet(num);
而这个 returns 和 Collections$SortedSet
。我的问题是这不能转换为 TreeSet
- 它只能转换为 SortedSet
。我无法更改 num 对象的 class,因此它 必须 转换为 TreeSet
.
有谁知道我如何将 Collections$SortedSet
转换为 TreeSet
,或者我可以用来同步此 TreeSet
的其他方法?
没有这样的实现,但您可以轻松实现。只需扩展 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
}