[英]In referencing a java object, what is the difference between the two?
I'm fairly new to java. 我是java的新手。 I have a simple question.
我有一个简单的问题。
public Object getObject() {
//`do something that results to an Object`
return object;
}
1st: 第一:
Object object1 = new Object();
object1 = getObject();
2nd: 第二名:
Object object1 = getObject();
What is the difference between the two? 两者有什么区别? Which is better to use?
哪个更好用?
它们返回相同的内容(将“;”添加到第一个示例的第一行:P)。
The difference is that in the first case, you are first making a new Object and immediately throwing it away on the next line when you replace it with the result of getObject(). 区别在于,在第一种情况下,您首先要制作一个新的Object,然后在用getObject()的结果替换它时立即将其丢弃在下一行。
If you modify it slightly, you'll see that the two objects are different instances. 如果稍加修改,您将看到两个对象是不同的实例。
Object object1 = new Object();
System.out.println(object1);
object1 = getObject();
System.out.println(object1);
When you run that, not that the printed value is different. 运行该命令时,并不是说打印值不同。 This is because there were two different values assigned to object1.
这是因为有两个不同的值分配给object1。
This is not a pattern you want to be using. 这不是您要使用的模式。 All you are doing here is making an object that needs to be garbage collected.
您在这里所做的只是制作一个需要垃圾回收的对象。
I'm also not sure that case 1 even works. 我也不确定情况1是否有效。 It won't compile, because object is an undefined variable.
它不会编译,因为object是一个未定义的变量。 You would need to change it to
return new Object();
您将需要更改它以
return new Object();
That way the value to return is defined. 这样就定义了要返回的值。
Really what you want to do is just say Object object = new Object();
真的,您只想说
Object object = new Object();
Adding the getObject function really isn't buying you anything. 添加getObject函数实际上并没有买任何东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.