Skip to content

Latest commit

 

History

History
60 lines (42 loc) · 1.78 KB

Ex_1_2_16.md

File metadata and controls

60 lines (42 loc) · 1.78 KB
title date draft tags categories
算法4 Java解答 1.2.16
2019-02-22 07:35:22 +0800
false
JAVA
技术
归档

1.2.16

问题:

Rational numbers. Implement an immutable data type Rational for rational numbers that supports addition, subtraction, multiplication, and division.

2019-06-24-003

分析:

In mathematics, a rational number is any number that can be expressed as the quotient or fraction p/q of two integers.

An immutable class is good for caching purpose because you don’t need to worry about the value changes. Other benefit of immutable class is that it is inherently thread-safe, so you don’t need to worry about thread safety in case of multi-threaded environment.

immutable类的写法

To create an immutable class in java, you have to do following steps.

  • Declare the class as final so it can’t be extended.
  • Make all fields private so that direct access is not allowed.
  • Don’t provide setter methods for variables
  • Make all mutable fields final so that it’s value can be assigned only once.
  • Initialize all the fields via a constructor performing deep copy.
  • Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

equals 的写法

    @Override
    public boolean equals(Object b) {
      if (this == b)
        return true;
      if (b == null)
        return false;
      if (this.getClass() != b.getClass())
        return false;
      _Rational that = (_Rational) b;
      return this.numerator == that.numerator
          && this.denominator == that.denominator;
    }

参考:

how-to-create-immutable-class-in-java