为什么不声明一个数组最终使它在Java中不可变? [英] Why won't declaring an array final make it immutable in Java?

查看:117
本文介绍了为什么不声明一个数组最终使它在Java中不可变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不声明一个数组最终使它在Java中不可变?不宣布最终意味着它无法改变吗?

Why won't declaring an array final make it immutable in Java? Doesn't declaring something final mean it can't be changed?

来自与不可变数组相关的问题很明显,声明一个数组final不会使它不可更改。

From question related to immutable array it's clear that declaring an array final doesn't make it unchangeable.

以下是可能的。

final int[] array = new int[] {0, 1, 2, 3};
array[0] = 42;

我的问题是:在这里宣布决赛的功能是什么?

My question is: What is the function of declaring final here then?

推荐答案

final 仅与其标记的参考有关;在Java中没有不可变数组这样的东西。当你说

final is only about the reference that is marked by it; there is no such thing as an immutable array in Java. When you say

private final int[] xs = new int[20];

您将不被允许说

xs = new int[10];

稍后。这是全部 最终的内容。更一般地,确保对象是不可变的通常是艰苦的工作并且充满了一系列细微之处。语言本身并没有为此提供太多开箱即用的结果。

later on. That's all what final is about. More generally, ensuring that an object is immutable is often hard work and full of a range of subtleties. The language itself doesn't give much to this end out of the box.

这篇关于为什么不声明一个数组最终使它在Java中不可变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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