Write an immutable Colour class with a private constructor and a static factory rgb(r, g, b) that reuses existing objects from a static cache; show how many objects were actually created.
Solution
Main.java
import java.util.HashMap;
import java.util.Map;
final class Colour {
private static final Map<Integer, Colour> CACHE = new HashMap<>();
private static int created = 0;
private final int r, g, b;
private Colour(int r, int g, int b) { this.r = r; this.g = g; this.b = b; created++; }
static Colour rgb(int r, int g, int b) {
if ((r | g | b) < 0 || r > 255 || g > 255 || b > 255) throw new IllegalArgumentException("0-255 only");
int key = (r << 16) | (g << 8) | b;
return CACHE.computeIfAbsent(key, k -> new Colour(r, g, b));
}
static Colour hex(String h) {
int v = Integer.parseInt(h.substring(1), 16);
return rgb(v >> 16 & 0xFF, v >> 8 & 0xFF, v & 0xFF);
}
static int created() { return created; }
@Override public String toString() { return String.format("#%02X%02X%02X", r, g, b); }
}
public class Main {
public static void main(String[] args) {
Colour red = Colour.rgb(255, 0, 0);
Colour red2 = Colour.hex("#ff0000");
Colour teal = Colour.hex("#008080");
Colour teal2 = Colour.rgb(0, 128, 128);
System.out.println(red + " " + teal + " " + (red == red2) + " " + (teal == teal2) + " created=" + Colour.created());
}
}
Output Verified by compiling and running
#FF0000 #008080 true true created=2
Because Colour is immutable, sharing one object per value is safe – the same idea as Integer.valueOf caching -128..127.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!