Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an 2D ArrayList immutable?

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!

like image 503
zw324 Avatar asked Oct 10 '22 16:10

zw324


1 Answers

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);    
like image 83
Rob Harrop Avatar answered Nov 01 '22 11:11

Rob Harrop