I want to modify the elements of the ArrayList and TreeSet simultaneously.
Ex. When I modify an element from the TreeSet, the corresponding element in the Arraylist is modified too.
I want to modify the elements of the ArrayList and TreeSet simultaneously.
Ex. When I modify an element from the TreeSet, the corresponding element in the Arraylist is modified too.
As long as you're adding the same object to both, this is exactly what should happen. (Am I missing something?)
In Java, objects in collections are stored with their references. Therefore if you modify an object, it will be updated on everywhere it is referenced from. You shouldn't be concerned about that.
In order to use both synchronized you should implement a new class, here's the template:
class MyCollection{
private TreeSet treeSet;
private ArrayList arrayList;
public synchronized void add(Object o){
treeSet.add(o);
arrayList.add(o);
}
}
Things I considered above:
synchronized
keyword to provide consistent multithreaded concurrency.Things I haven't considered above:
boolean
as all java Collection
s do.You should implement your own code for better solution, but generally, that's the idea.
EDIT: Another solution is to write your own TreeSet and ArrayList wrappers (that uses treeset and arraylist underneath) and when something is added, since you'll override that add()
method, you can add the other thing. But this is not a loose coupling practice. Maybe there's another solution with Observer Framework.