Effective Java 第十五条:使可变性最小化

Posted 阿蛮家

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Effective Java 第十五条:使可变性最小化相关的知识,希望对你有一定的参考价值。

复数类Complex:

public final class Complex 
    private final double re;
    private final double im;

    public Complex(double im, double re) 
        this.im = im;
        this.re = re;
    

    public double realPart()
        return im;
    

    public double imaginaryPart()
        return re;
    

    public Complex add(Complex c)
        return new Complex(re + c.re, im + c.im);
    

    public Complex subtract(Complex c)
        return new Complex(re - c.re, im - c.im);
    

    public Complex motiply(Complex c)
        return new Complex(re * c.re - im * c.im, re * c.re + im * c.im);
    

    public Complex divide(Complex c)
        double temp = im * c.im + re * c.re;
        return new Complex((re * c.re + im * c.im) / temp, (re * c.re - im * c.im) / temp);
    

    @Override
    public int hashCode() 
        int result = 17 + hashDouble(re);
        result = 31 * result + hashDouble(im);
        return result;
    

    private int hashDouble(double val)
        long longBits = Double.doubleToLongBits(val);
        return (int)(longBits ^ (longBits >>> 32));
    

    @Override
    public boolean equals(Object obj) 
        if(obj == this)
            return true;
        if(!(obj instanceof Complex))
            return false;
        Complex c = (Complex) obj;
        return Double.compare(im, c.im) == 0 &&
                Double.compare(re , c.re) == 0;
    

    @Override
    public String toString() 
        return "+ re + " + re +" + im + " + im;
    

测试:

public class ComplexText 
    public static void main(String[] args) 
        Complex complex = new Complex(1.0,2.0);
        Complex complex1 = new Complex(2.0,3.0);
        System.out.println(complex.add(complex1));
        System.out.println(complex.divide(complex1));
        System.out.println(complex.subtract(complex1));
        System.out.println(complex.motiply(complex1));
    



以上是关于Effective Java 第十五条:使可变性最小化的主要内容,如果未能解决你的问题,请参考以下文章

Effective Java 第五条:避免创建不必要的对象

图灵学院Java架构师要掌握哪些技能?你所不知的十五条秘密

Effective Java2读书笔记-类和接口

[读书笔记]Effective Java 第四章

Effective Java 读书笔记之三 类和接口

王艳 《面向对象程序设计》第十五周学习总结