这两个java方法定义相同变量的重点是什么

时间:2014-09-14 00:22:40

标签: java

我是Java&我正在浏览图书馆,但我对两种方法感到困惑:

public class Complex {

    /** The real part of a complex number. */
    private double real;

    /** The imaginary part of a complex number. */
    private double imaginary;

    public void divideComplex(Complex a, Complex b) {
      this.real = a.real * b.real + a.imaginary * b.imaginary;
      this.imaginary = a.imaginary * b.real - a.real * b.imaginary;
      this.scaleComplex(this, b.squaredMagnitudeComplex());
    }

    public void scaleComplex(Complex a, double b) {
      this.real = a.real / b;
      this.imaginary = a.imaginary / b;
    }

}

我在这里遗漏了什么或者不能divideComplex这样做:

    public void divideComplex(Complex a, Complex b) {
      Complex newComplex = new Complex { 
        val real = this.real = a.real * b.real + a.imaginary * b.imaginary;
        val imaginary = this.imaginary = a.imaginary * b.real - a.real * b.imaginary;
      }
      this.scaleComplex(newComplex, b.squaredMagnitudeComplex());
    }

Click here to view source

1 个答案:

答案 0 :(得分:2)

原始代码与您的代码之间的区别在于原始代码会对调用Complex的{​​{1}}进行更改,而您的代码不会更改它,因为它会创建一个新的本地代码divideComplex

但是,然后调用Complex,它会覆盖当前对象的值。所以最后的结果确实相同。但是性能可能会有所不同:在您的代码中,创建并丢弃新对象,而原始代码就地工作而无需分配新内存。原始版本应该在内存使用和性能方面更高效(我说“应该”,因为JVM优化器不是那么可预测的。)