Clamp a value between bounds with a single clear call.
Porównanie kodu
✕ Java 8
// Clamp value between min and max
int clamped =
Math.min(Math.max(value, 0), 100);
// or: min and max order confusion
✓ Java 21+
int clamped =
Math.clamp(value, 0, 100);
// value constrained to [0, 100]
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Self-documenting
clamp(value, min, max) is unambiguous.
Less error-prone
No more swapping min/max order by accident.
All numeric types
Works with int, long, float, and double.
Stare podejście
Nested min/max
Nowoczesne podejście
Math.clamp()
Od JDK
21
Poziom trudności
Początkujący
Wsparcie JDK
Math.clamp()
Dostępne
Widely available since JDK 21 LTS (Sept 2023)
Jak to działa
Math.clamp(value, min, max) constrains a value to the range [min, max]. Clearer than nested Math.min/Math.max and available for int, long, float, and double.
Powiązana dokumentacja