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?
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.
It's impossible with primitive arrays.
You will have to use the Collections.unmodifiableList()
as you already did in your code.
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