I'm looking to solve the following problem:
Starting with a collection A, I want to pass some kind of 'view' on that collection (say collection B) to a certain method. The view B does not necessary contain all the elements of the original collection A. If in this method objects are added to or removed from the view (collection B), these changes should also be reflected on the original collection A as well.
For instance (pseudo-code):
Start situation:
Collection A = {1, 2, 3};
View-on-collection B = {1, 2};
Method call:
someMethod(B) {
B.add(4);
B.remove(2);
}
End situation:
Collection A = {1, 3, 4};
Does anyone know a neat solution to this problem?
Java Immutable Collections (7 answers) Closed 4 months ago. From the Collections Framework Overview: Collections that do not support modification operations (such as add , remove and clear ) are referred to as unmodifiable. Collections that are not unmodifiable are modifiable.
View in Java Collections Framework is a lightweight object which implements Collection or Map interface but is not a real collection in a traditional sense. In fact, view does store objects inside but references another collection, array or a single object and uses it to provide the data to a user.
Generally, collections with some kind of internal structure don't watch for changes in their elements, and their structure will be destroyed if you modify the elements (in ways that change the property that the structure is based on). This holds for TreeSet as well.
Arraylist collection class allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not synchronized. The answer to the question- Which collection class allows you to grow or shrink? is java. util. Arraylist.
One way is to use List.sublist()
:
public static void main(String[] args) {
List<Integer> aList = new ArrayList<Integer>(Arrays.asList(1,2,3));
List<Integer> view = aList.subList(0, 2);
view.add(new Integer(4));
view.remove(new Integer(2));
System.out.println("aList: " + aList);
System.out.println("view : " + view);
}
Another more general way would be through Guavas Collections2.filter()
, that lets you define a predicate to control which objects should be in the view:
public static void main(String[] args) {
List<Integer> aList = new ArrayList<Integer>(Arrays.asList(1,2,3));
@SuppressWarnings("unchecked")
Collection<Integer> view = Collections2.filter(aList, new Predicate() {
public boolean apply(Object arg0) {
return ((Integer) arg0).intValue() % 3 != 0;
}});
view.add(new Integer(4));
view.remove(new Integer(2));
System.out.println("aList: " + aList);
System.out.println("view : " + view);
}
Both examples print
aList: [1, 4, 3]
view : [1, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With