Java changing value of final array element

后端 未结 4 724
长情又很酷
长情又很酷 2021-01-14 08:17

I am trying to understand what happens if I reassign a value to array element which is final, this is the code :

public class XYZ {
    private static final          


        
4条回答
  •  耶瑟儿~
    2021-01-14 09:08

    Arrays are mutable Objects unless created with a size of 0.Therefore,you can change the contents of an array.final only allows you to prevent the reference from being changed to another array Object.

    final String[] ABC ={"Hello"};
    ABC[0]="Hi" //legal as the ABC variable still points to the same array in the heap
    ABC = new String[]{"King","Queen","Prince"}; // illegal,as it would refer to another heap Object
    

    I suggest you use Collections.unmodifiableList(list) to create a immutable List.See the javadoc here (unmodifibale list).

    You can do the following

    String[] ABC = {"Hello"};
    List listUnModifiable = Collections.unmodifiableList(java.util.Arrays.asList(ABC));
    

    At any point of time,you can get the array by calling listUnModifiable.toArray();

提交回复
热议问题