最后一个数组元素的Java的变化值 [英] Java changing value of final array element

查看:223
本文介绍了最后一个数组元素的Java的变化值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果我重新分配一个值,这是最后的数组元素会发生什么,这是code:

 公共类XYZ {
    私有静态最后的String [] ABC = {你好};    公共静态无效的主要(字串[] args){
        的System.out.println(ABC [0]);        ABC [0] =世界!!!;
        的System.out.println(ABC [0]);    }
}

ABC是最后一个数组,并在第一个位置它有你好开始,但是当我重新分配给世界!!!应该要么在骑previous值,或者它应该给编译错误重新分配给最后一个变量。该程序运行良好,这是输出:

 运行:
你好
 世界!!!
BUILD SUCCESSFUL(总时间:0秒)


解决方案

阵列是可变的,对象,除非有大小0.Therefore创建,你可以改变的内容一个数组。最后只允许prevent被更改到另一个数组对象的引用。

 最终的String [] ABC = {你好};
ABC [0] =嗨法律//作为ABC变量仍指向堆在同一阵列
ABC =新的String [] {王,皇后,王子}; //非法的,因为它会引用另一堆对象

我建议你使用 Col​​lections.unmodifiableList(名单) 这里<创建一个不可改变List.See的Javadoc一href=\"http://download.oracle.com/javase/7/docs/api/java/util/Collections.html#unmodifiableList(java.util.List)\"相对=nofollow>(unmodifibale列表)。

您可以执行以下操作

 的String [] ABC = {你好};
清单&LT;串GT; listUnModifiable = Collections.unmodifiableList(java.util.Arrays.asList(ABC));

在任何时候,你可以通过调用获取数组 listUnModifiable.toArray();

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 String[] ABC = {"Hello"};

    public static void main(String[] args){
        System.out.println(ABC[0]);

        ABC[0] = " World!!!";
        System.out.println(ABC[0]);

    }
}

ABC is final array and at first position it have "Hello" initially, but when I reassign it to " World!!!" it should either over ride the previous value or it should give compilation error for reassigning to final variable. This program runs fine and this is the output :

run:
Hello
 World!!!
BUILD SUCCESSFUL (total time: 0 seconds)

解决方案

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<String> listUnModifiable = Collections.unmodifiableList(java.util.Arrays.asList(ABC));

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

这篇关于最后一个数组元素的Java的变化值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆