简体   繁体   English

方法创建新实例

[英]Method Creates new instance

When a method returns an object, does that method automatically create a new instance of that object in memory? 当方法返回一个对象时,该方法是否会在内存中自动创建该对象的新实例?

For example: 例如:

In Java BigInteger class , I use the add method where num1 , and num2 , lets say, are BigIntegers . Java BigInteger class ,我使用add方法,其中num1num2就是BigIntegers

num1.add(num2);

Then I reference it by the same type as in: 然后我用与以下相同的类型引用它:

BigInteger a = num1.add(num2);

This works and gets the correct data. 这有效并获得正确的数据。 So the method will create a new instance of that object on the stack? 那么该方法将在堆栈上创建该对象的new instance

Just making sure I'm correct about my assumption. 只是确保我对我的假设是正确的。

Thanks. 谢谢。

bigInteger.add() does return a new instance, but not all methods do. bigInteger.add()确实返回一个新实例,但并非所有方法都返回。

What usually returns new object instances that you may run into regularly are: 通常返回您可能经常遇到的新对象实例的是:

  • Constructors 构造函数
  • Factorys/Builders 厂区/建筑工地
  • methods operating on immutable objects 对不可变对象进行操作的方法

BigInteger 's add method says that it returns a BigInteger , doesn't say a new BigInteger , but given that the docs also state that BigInteger is immutable , then you can know it's not returning the this object with a modification, so chances are that it's a new object (I suppose it's possible to be some cached object already representing that state, but even if it was, your usage of BigInteger wouldn't change.). BigIntegeradd方法说它返回一个BigInteger ,并没有说new BigInteger ,但是假设文档还声明BigInteger是不可变的 ,那么你可以知道它没有通过修改返回this对象,所以很有可能它是一个新对象(我想它可能是已经代表该状态的一些缓存对象,但即使它是,你对BigInteger的使用也不会改变。)。

It depends. 这取决于。

With your BigInteger example, it is returning a new instance of the object. 使用BigInteger示例,它将返回对象的新实例。

However with something like StringBuilder, you can do 但是使用像StringBuilder这样的东西,你可以做到

stringBuilder.append("this").append("is").append("a").append("string");

and each .append(String) is returning the same original object, it just allows you to chain the calls together. 并且每个.append(String)返回相同的原始对象,它只允许您将调用链接在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM