0

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);
        }
    }

}
JSN
  • 2,035
  • 13
  • 27

1 Answers1

1

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

Dmytro Chekunov
  • 192
  • 1
  • 10