如果您不引用它,Java中的对象会发生什么,例如:myString.concat(" that“) [英] what happens to an object in Java if you do not reference it, like here : myString.concat("that")

查看:93
本文介绍了如果您不引用它,Java中的对象会发生什么,例如:myString.concat(" that“)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String myString = "this";
//string is immutable

myString.concat(" that");
//a new object is created but not assigned to anything

System.out.println(myString); //prints out "this"

我更喜欢编译时错误 - 为什么不是这种情况?当调用它而不提供返回类型时,同样的问题可以应用于任何具有返回类型的方法。

I would prefer a compile time error - why is this not the case ? The same question can be applied to any method with a return type, when it is called without supplying return type.

public myObject doStuff(...whatever){
 //define my method
 return anObject;
}

可以调用而不提供引用/变量来保存返回类型: / p>

can be called without providing a reference/variable to hold the return type:

MyObject newObject = doStuff(); //works
doStuff(); //works too without assigning return object


推荐答案

对象将即可创建并有资格进行垃圾收集(即很快就会收集垃圾)。

The object will be created and eligible for garbage collection right away (i.e. it will probably be garbage collected pretty soon).

这不是编译时错误的原因是并非每个方法都是返回一个方法要求您使用该返回值。有些方法只是因为它们的副作用而被调用。

The reason this is not a compile time error is that not every method that returns a method requires you to use that return value. Some methods are only called for their side effects.

一个很好的例子是 Collection.add() :它返回 boolean object,但通常情况下,调用代码对该结果不感兴趣而只是忽略它。

A good example is Collection.add(): it returns a boolean object, but more often than not, the calling code is not interested in that result and simply ignores it.

同样 StringBuilder.append() 返回 StringBuilder 实例,以便您可以链接调用。但忽略该返回值并简单地使用 myStringBuilder.append(foo);

Similarly StringBuilder.append() returns the StringBuilder instance so that you can chain the calls. But it's also perfectly valid to ignore that return value and simply use myStringBuilder.append("foo");.

这篇关于如果您不引用它,Java中的对象会发生什么,例如:myString.concat(" that“)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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