Reputation: 3930
Googled for it, found plenty of code. But any of them gave me what I want. I want to make an ordinary array Immutable. I tried this:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class test {
public static void main(String[] args) {
final Integer array[];
List<Integer> temp = new ArrayList<Integer>();
temp.add(Integer.valueOf(0));
temp.add(Integer.valueOf(2));
temp.add(Integer.valueOf(3));
temp.add(Integer.valueOf(4));
List<Integer> immutable = Collections.unmodifiableList(temp);
array = immutable.toArray(new Integer[immutable.size()]);
for(int i=0; i<array.length; i++)
System.out.println(array[i]);
array[0] = 5;
for(int i=0; i<array.length; i++)
System.out.println(array[i]);
}
}
But it doesnt work, I CAN assign a 5 into array[0] ... Is there any way to make this array immutable?
Upvotes: 9
Views: 10064
Reputation: 8022
You can also use Guava's ImmutableList, a high-performance, immutable, random-access List implementation that does not permit null elements. Unlike Collections.unmodifiableList(java.util.List)
, which is a view of a separate collection that can still change, an instance of ImmutableList contains its own private data and will never change.
Upvotes: 1
Reputation: 121740
If you want to use it as an array, you can't.
You have to create a wrapper for it, so that you throw an exception on, say, .set()
, but no amount of wrapping around will allow you to throw an exception on:
array[0] = somethingElse;
Of course, immutability of elements is another matter entirely!
NOTE: the standard exception to throw for unsupported operations is aptly named UnsupportedOperationException
; as it is unchecked you don't need to declare it in your method's throws
clause.
Upvotes: 5
Reputation: 9785
It's impossible with primitive arrays.
You will have to use the Collections.unmodifiableList()
as you already did in your code.
Upvotes: 3