Search code examples
javaarraysfinal

How to make elements of array immutable?


I've a final String array and pass it to a method. The method is able to change the values of elements as shown below. How to protect the elements of final String array from being modified?

class Test {

    public static void main(String[] arguments) {
        final String[] finalNames = new String[] { "Name1", "Name2", "Name3" };
        iterateNames(finalNames);
    }

    private static void iterateNames(final String[] finalNames) {

        //The below assignment should be prevented

        finalNames[0] = "ChangedName1";

        for (String name : finalNames) {
            System.out.println(name);
        }
    }

}

Solution

  • Check out this answer. TL:DR: you need to use other data structure to get an immutable array.