At the moment I have a class Fraction that allows me to create Fractions in three different ways
- With one Integer, in this case the given Integer will be the numerator and the denominator will be set to 1
- With 2 Integers, the numerator and the denominator
- The Last method would be to parse a String that has to match the REGEX -?\d+/[1-9]\d*
The generated Fractions will be reduced as far as possible with the gcd.
public class Fraction extends Number {
public static final String REGEX = "-?\d+/[1-9]\d*";
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static Fraction parseFraction(String s) {
if (!s.matches(REGEX)) {
throw new RuntimeException("Parsing error");
}
String[] splitted = s.split("/");
return new Fraction(Integer.parseInt(splitted[0]),
Integer.parseInt(splitted[1]));
}
private int numerator;
private int denominator;
public Fraction(int numerator) {
this(numerator, 1);
}
public Fraction(int numerator, int denominator) {
if (denominator == 0) {
throw new RuntimeException("denominator == 0 is not possible");
}
int gcd = Fraction.gcd(numerator, denominator);
if (denominator / gcd < 0) {
gcd *= -1;
}
this.numerator = numerator / gcd;
this.denominator = denominator / gcd;
}
}
What I want to implement now is that Instances of Fraction with same numerator and denominator have the same Reference e.g.
*Fraction.parseFraction("1/2").equals(Fraction.parseFraction("2/4"))*
should return true.
I looked into some chapters about Generics and Bounds, but im unsure if that is even the right direction of what I need. Should the Fraction class be bounded to String and Integer?
-?\d+/[1-9]\d*
, with\
instead of//
?private
(or package private), and using a creational pattern. You'll need to populate (and maintain) a pool of references.