问题描述
假设我有一个值
,我通常会将其钳制到一个范围,这里的范围是 [0..1]
。也就是说,如果它低于范围开始,将其增加到范围开始,它高于范围结束,将其减少到范围结束。
Suppose I have a value
, I usually do this to "clamp" it to a range, here the range [0..1]
. That is if it is below the range start, increase it to the range start, it above the range end, reduce it to the range end.
clampedValue = Math.max(0, Math.min(1, value));
是否有内置函数用于钳位到范围?
Is there any built in function for clamping to a range?
推荐答案
看了另一个答案中提供的通用钳位方法,值得注意的是,它有考虑为原始类型。
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);
这将使用 Float
包装类,导致3个盒子操作,每个参数一个,以及返回类型的1个unbox操作。
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.
这篇关于java有钳位功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!