Having looked at the generic clamp method offered up in another answer, it is worth noting that this has boxing/unboxing considerations for primitive types.
public static <T extends Comparable<T>> T clamp(T val, T min, T max) {...}
float clampedValue = clamp(value, 0f, 1f);
This will use the Float
wrapper class, resulting in 3 box operations, one for each parameter, and 1 unbox operation for the returned type.
To avoid this, I would just stick to writing it long hand or use a non-generic function for the type you want:
public static float clamp(float val, float min, float max) {
return Math.max(min, Math.min(max, val));
}
Then just overload with identical methods for every primitive type you require.