Java对象分配 [英] Java Object Assignment

查看:140
本文介绍了Java对象分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,我对于对象分配有一些问题。例如,

I am new to Java and I have some questions in mind regarding object assignment. For instance,

Test t1 = new Test();
Test t2 = t1;
t1.i=1;

假设变量 i 在Test class中定义,我是否正确假设t1和t2都指向同一个对象,其中修改 t1.i = 1 同时影响 t1 t2 ?实际上我测试了它,看起来我是对的。但是,当我在 String 上尝试相同的操作时,修改仅发生在另一侧不受影响的一侧。这背后的原因是什么?

Assuming variable i is defined inside Test class, am I right to assume both t1 and t2 point to the same object where the modification t1.i=1 affects both t1 and t2? Actually I tested it out and seems like I was right. However when I try the same thing on String, the modification happens only on one side where the other side is unaffected. What is the reason behind this?

编辑:我尝试使用String的情况。

The case I tried with String.

String s1 = "0";
String s2 = s1;          
s1 = "1";
System.out.println(s1);
System.out.println(s2);

我通过测试String上的案例来实现我的错误,因为它是不可变的。我认为 s1 =1修改字符串的情况实际上是将参数1返回给s1。不过,我的问题仍然存在。 测试t2 = t1; 导致t2和t1指向同一个对象,或者现在每个对象都有?这种情况是否适用于Java上的所有对象?

I realise my mistake by testing the cases on String since it is immutable. The situation where I thought s1="1" modify the string is in fact returning the reference of "1" to the s1. Nevertheless, my question remains. Does Test t2 = t1; cause both t2 and t1 point to the same object or each now have their own objects? Does this situation applies on all objects on Java?

推荐答案

你是对的,但字符串是一个特例;在这种情况下,它们是不可变的,就像原始一样。

You are right, but Strings are a special case; they are immutable and act like primitives in this case.

@newacct

我引用 http://docs.oracle.com/javase/tutorial/java/data/strings.html


注意:String类是不可变的,因此一旦创建了
String对象就不能改变。 String类有一个数字
的方法,其中一些将在下面讨论,看起来是
修改字符串。由于字符串是不可变的,这些方法实际上是
做的是创建并返回一个包含
结果的新字符串。

Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.

这就是使字符串成为特例的原因。如果您不知道这一点,您可能希望引用中讨论的方法不会返回新的字符串,这会导致意外的结果。

This is what makes strings a special case. If you don't know this, you might expect the methods discussed in the quote not to return new strings, wich would lead to unexpected results.

@ user1238193

@user1238193

考虑以下问题:测试t2 = t1;导致t2和t1指向同一个对象,或者现在每个都有自己的对象吗?这种情况是否适用于所有对象Java?

Considering your following question: "Does Test t2 = t1; cause both t2 and t1 point to the same object or each now have their own objects? Does this situation applies on all objects on Java?"

t1和t2将指向同一个对象。对于任何java对象(包括不可变对象)

t1 and t2 will point to the same object. This is true for any java object (immutable objects included)

这篇关于Java对象分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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