java中的不可变类更改值导致问题
需要了解案例1和案例2。请帮忙进来 我的问题是字符串是不可变的类。所以如果我们改变了 字符串值,然后它将创建其他对象,但如果我们创建自己的对象 不可变类,那么一旦我们 根据最终变量指定值java中的不可变类更改值导致问题,java,Java,需要了解案例1和案例2。请帮忙进来 我的问题是字符串是不可变的类。所以如果我们改变了 字符串值,然后它将创建其他对象,但如果我们创建自己的对象 不可变类,那么一旦我们 根据最终变量指定值 String是一个不可变的类,意味着无法[*]更改给定字符串对象的值。当您分配s1=“test”时,您正在为同一变量分配一个不同的对象。这类似于做s=newstudent(“新名字”,123) 当然,您也可以将s定义为final,以防止重新分配给它,但这与s的类型是不可变的事实无关 [*]至少在“正确”的方式下
String
是一个不可变的类,意味着无法[*]更改给定字符串对象的值。当您分配s1=“test”
时,您正在为同一变量分配一个不同的对象。这类似于做s=newstudent(“新名字”,123)
当然,您也可以将s
定义为final
,以防止重新分配给它,但这与s
的类型是不可变的事实无关
[*]至少在“正确”的方式下,不使用反射、字节码操作和其他“秘密”技术在案例2中,字符串变量s不是最终变量,因此可以为其指定不同的值。
如果将其设置为
final String s=“test”,则将得到与案例1相同的错误代码>这似乎与类的不变性无关。创建该类的一个实例,然后通过创建一个同名字符串变量立即对其进行阴影处理,然后创建另一个同名变量。您没有更改任何涉及的对象。
// An immutable class
public final class Student {
final String name;
final int regNo;
public Student(String name, int regNo) {
this.name = name;
this.regNo = regNo;
}
public String getName() {
return name;
}
public int getRegNo() {
return regNo;
}
}
class Test {
public static void main(String args[]) {
Student s = new Student("ABC", 101);
System.out.println(s.name);
System.out.println(s.regNo);
// Case 1 :: s.regNo = 102; It will throw exception because we can't change the final value
// Case 2 ::
String s = "test"; // String immutable class so as per above class if I try to change the value of s then it should also causing issue or throw exception
But it will not throw any exception.
String s = "test1"; // It will not throw any exception but in case 1 it will throw exception
}
}