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

}
1
  • 4
    Use defensive copies, don't send the original array. Send a copy of that array Commented Jul 11, 2017 at 6:44

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.