Skip to content

Instantly share code, notes, and snippets.

@hishidama
Created October 19, 2016 03:56
Show Gist options
  • Save hishidama/ea5cf9e781fccc757defce5f1ac60260 to your computer and use it in GitHub Desktop.
Save hishidama/ea5cf9e781fccc757defce5f1ac60260 to your computer and use it in GitHub Desktop.
toStringにロジックを書いたFizzBuzz
package example;
import java.util.function.Supplier;
public class ToStringFizzBuzz {
private final int value;
public ToStringFizzBuzz(int value) {
assert value >= 1;
this.value = value;
}
@Override
public String toString() {
Supplier<String> s = () -> equals(3) ? "Fizz" : equals(5) ? "Buzz" : equals(15) ? "FizzBuzz" : Integer.toString(value);
if (value == 1) {
return s.get();
}
return new ToStringFizzBuzz(value - 1) + System.lineSeparator() + s.get();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ToStringFizzBuzz) {
return value == ((ToStringFizzBuzz) obj).value;
}
if (obj instanceof Integer) {
return hashCode() == (int) obj;
}
return false;
}
@Override
public int hashCode() {
boolean b3 = value % 3 == 0;
boolean b5 = value % 5 == 0;
return (b3 && b5) ? 15 : b3 ? 3 : b5 ? 5 : 0;
}
public static void main(String... args) {
System.out.println(new ToStringFizzBuzz(100));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment