Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to make an ordinary array immutable in Java?

Tags:

java

arrays

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?

like image 810
yak Avatar asked Jun 15 '13 11:06

yak


2 Answers

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.

like image 178
fge Avatar answered Sep 22 '22 08:09

fge


It's impossible with primitive arrays.

You will have to use the Collections.unmodifiableList() as you already did in your code.

like image 38
darijan Avatar answered Sep 21 '22 08:09

darijan