【问题标题】:Difference between regular objects and Strings常规对象和字符串之间的区别
【发布时间】:2015-09-01 09:16:29
【问题描述】:
public class StringHandling {

 public static void main(String[] args) {
    String a = "Hello World";
    Test b = new Test(5);
    String c = a;
    Test d = b;
    System.out.println("String a = " + a);
    System.out.println("Test b = " + b.a); 
    System.out.println("String c = " + c);
    System.out.println("Test d = " + d.a);

    System.out.println();
    System.out.println();
    a = "Hello People";
    b.a = 15;

    System.out.println("String a = " + a);
    System.out.println("Test b = " + b.a); 
    System.out.println("String c = " + c);
    System.out.println("Test d = " + d.a);
 }
}

输出: ac 不同,bd 相同,为什么? StringTest 都是 Objects。 请解释一下常规对象和字符串之间的区别。非常感谢。

【问题讨论】:

  • 您没有对每个操作执行相同的操作,因此您不能期望相同的结果。
  • 请解释一下。谢谢
  • a = "Hello People"b.a = 15 有什么区别?解决这个问题,你就会得到答案。与我们用勺子喂食相比,你会学到更多。
  • 谢谢蜘蛛鲍里斯,以后我会小心的

标签: java string object reference


【解决方案1】:

输出:a 和 c 不同

您分配了“c”,后来更改了“a”,因此它们不同。

为什么b和d一样?

您将b 分配给d,但您没有替换任何一个,所以它们仍然指向同一个对象。

【讨论】:

  • 好的,所以当我更改 a 时,我创建了新的字符串对象。谢谢。
  • @AbuBakkarSiddique 值得记住的是,areference 而不是 object 当您更改 a 时,您已经更改了 reference对象,而不是改变对象本身。当您分配 b.a = 时,您正在更改 b 所指的对象。
【解决方案2】:

一开始ac 指向同一个String 对象。但随后分配了

a = "Hello People"

a 持有对另一个字符串对象的引用,因此它们是不同的。

Test 实例的情况正好相反。他们仍然持有对同一个对象的引用。所以你基本上用

的赋值来改变对象的属性
b.a = 15

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-18
    • 2015-05-25
    • 2017-01-29
    • 2013-06-10
    • 2016-10-22
    • 1970-01-01
    • 2011-03-19
    相关资源
    最近更新 更多