Java - limit number between min and max(Java - 最小值和最大值之间的限制数)
问题描述
只要数字在限制范围内,我想返回,否则返回限制的最大值或最小值.我可以结合使用 Math.min
和 Math.max
.
I want to return the number as long as it falls within a limit, else return the maximum or minimum value of the limit. I can do this with a combination of Math.min
and Math.max
.
public int limit(int value) {
return Math.max(0, Math.min(value, 10));
}
我想知道是否存在我忽略的现有 limit
或 range
函数.
如果第三方库很常见(例如:Commons 或 Guava),欢迎使用它们
I'm wondering if there's an existing limit
or range
function I'm overlooking.
3rd party libraries welcome if they are pretty common (eg: Commons or Guava)
推荐答案
从第 21 版开始,Guava包括 Ints.constrainToRange()
(以及其他原语的等效方法).来自发行说明:
As of version 21, Guava includes Ints.constrainToRange()
(and equivalent methods for the other primitives). From the release notes:
添加了 constrainToRange([type] value, [type] min, [type] max)
方法,将给定值限制在 min
定义的封闭范围内,并且max
值.如果它在范围内,则返回值本身,如果低于范围,则返回 min
,如果高于范围,则返回 max
.
added
constrainToRange([type] value, [type] min, [type] max)
methods which constrain the given value to the closed range defined by themin
andmax
values. They return the value itself if it's within the range, themin
if it's below the range and themax
if it's above the range.
由@dimo414 复制自https://stackoverflow.com/a/42968254/122441.
Copied from https://stackoverflow.com/a/42968254/122441 by @dimo414.
不幸的是,这个版本是 2017 年 7 月的最新版本,并且在某些项目中(请参阅 https://stackoverflow.com/a/40691831/122441) Guava 已经破坏了向后兼容性,这需要我暂时保留在版本 19 上.我也很震惊,Commons Lang 和 Commons Math 都没有它!:(
Unfortunately this version is quite recent as of July 2017, and in some projects (see https://stackoverflow.com/a/40691831/122441) Guava had broken backwards compatibility that required me to stay on version 19 for now. I'm also shocked that neither Commons Lang nor Commons Math has it! :(
这篇关于Java - 最小值和最大值之间的限制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java - 最小值和最大值之间的限制数


- 获取数字的最后一位 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 转换 ldap 日期 2022-01-01