3

I am using a TreeSet in Java to hold a list of integers:

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

Since my application has multiple threads, I want to be able to access it synchronously. I'm using Collections.synchronizedSortedSet(num); and this returns a Collections$SortedSet. My problem is that this cannot be cast to a TreeSet- it can only be cast to a SortedSet. I cannot change the class of the num object, so it must be cast to a TreeSet.

Does anyone know how I might otherwise cast Collections$SortedSet to TreeSet, or another method by which I could synchronize this TreeSet?

Sameer Puri
  • 987
  • 8
  • 20

1 Answers1

2

There is no such implementation, but you can easily make one your on. Just extend TreeSet, and override it's methods with synchronized methods.

for example:

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
}
Nir Levy
  • 12,750
  • 3
  • 21
  • 38