In the project I am working on, I have a 2D ArrayList which represents some data:
private ArrayList<ArrayList<T>> data = null;
Now I need to return this ArrayList to some object, in order to let the object inspect it, but not modify it.
I found in the following post that a 2D ArrayList needs to be wrapped separately by the unmodifiable wrapper, but it does not mention how to do it:
Does the unmodifiable wrapper for java collections make them thread safe?
So my problem is: how to return an immutable 2D ArrayList from an existing 2D ArrayList? And in addition, what is the fastest way, since the data could be large in practice?
Thanks for all the inputs!
Use the Collections.unmodifiableList
method:
ArrayList<ArrayList<String>> source = new ArrayList<ArrayList<String>>();
List<ArrayList<String>> out = Collections.unmodifiableList(source);
Calling Collections.unmodifiableList
on the source
collection, does not make each nested list unmodifiable. You'll need to do this recursively on the list, if you want all nested lists to be unmodifiable. So:
ArrayList<ArrayList<String>> source = new ArrayList<ArrayList<String>>();
List<List<String>> temp = new ArrayList<List<String>>();
for (ArrayList<String> list : source) {
temp.add(Collections.unmodifiableList(list));
}
List<List<String>> out = Collections.unmodifiableList(temp);
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