A.S*_*hov -1 java string object new-operator
What is the difference between creating Object, for example in my code, type Obj with operator "new" and Object type String?
public class Objs {
int a;
public Objs(int a)
{
this.a = a;
}
public static void main(String[] args)
{
String str = new String("Hello");
String str1 = str; // (str1 == str) == true
str += ", world!!"; // after this (str1 == str) == false - Why?
Objs o = new Objs(4);
Objs o1 = o; //(o == o1) == true
o.a += 9; // after this (o == o1) == true also
}
}
Run Code Online (Sandbox Code Playgroud)
Why after I'm changing value of "str", references "str" and "str1" become not equal, but if I'm doing the same with class Obj references stay equal?
这里:
str += ", world!!"
Run Code Online (Sandbox Code Playgroud)
您正在创建具有更改后的值的新对象(这就是+operator String在Java中对s的工作方式)。这里:
o.a += 9;
Run Code Online (Sandbox Code Playgroud)
您正在修改对象的字段,但仍然是相同的引用。
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |