gpt4 book ai didi

java - 最终的、不可变的对象不是常量吗?

转载 作者:行者123 更新时间:2023-12-02 12:48:35 24 4
gpt4 key购买 nike

类(class)Integerint 的包装原始类型( https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html )。如果一个对象的状态在构造后无法更改,则该对象被认为是不可变的 ( https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html )。

我在这里理解的是,您只能更改 Integer 的值通过引用完全不同的 Integer 变量对象。

通过声明变量final我们可以保证以下几点:

Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.

再次,由immutable文档:

An object is considered immutable if its state cannot change after it is constructed.

所以是最终的、不可变的Integer不允许以任何方式更改其值。

如果这是正确的,为什么我们不允许声明 public static final Integer变量

following code声明 public static final Integer以不同的方式,它们都返回编译时错误:

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
public class Constants {
public static final String STRING_CONSTANT = "string_constant";
public static final int INTEGER_CONSTANT = 1; // allowed
//public static final Integer INTEGER_CONSTANT = 1; // not allowed
//public static final Integer INTEGER_CONSTANT = new Integer("1"); // not allowed
//public static final Integer INTEGER_CONSTANT = Integer.valueOf(1); // not allowed
}
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("STRING_CONSTANT = " + Constants.STRING_CONSTANT);
System.out.println("INTEGER_CONSTANT = " + Constants.INTEGER_CONSTANT);
}
}

抛出的异常是:

Main.java:12: error: Illegal static declaration in inner class Ideone.Constants
public static final Integer INTEGER_CONSTANT = 1;
^
modifier 'static' is only allowed in constant variable declarations
1 error

任何人都可以澄清为什么我们不允许声明 public static final Integer ,请问?

编辑:我有兴趣知道为什么 public static final Integer public static final String 时不允许和public static final int是,而不是找到可以编译的代码。

最佳答案

问题不在于常量的声明,而在于它是在非静态的内部类中声明的。将类的声明更改为静态即可:

public static class Constants {
public static final String STRING_CONSTANT = "string_constant";
public static final int INTEGER_CONSTANT = 1; // allowed
public static final Integer INTEGER_CONSTANT1 = 1;
public static final Integer INTEGER_CONSTANT2 = new Integer("1");
public static final Integer INTEGER_CONSTANT3 = Integer.valueOf(1);
}

关于java - 最终的、不可变的对象不是常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47136751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com