Java - 限制最小值和最大值之间的数字 [英] Java - limit number between min and max

查看:332
本文介绍了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));
}

我想知道是否存在限制范围我忽视的功能。

如果第三方图书馆很常见,欢迎加入(例如: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 the min and max values. They return the value itself if it's within the range, the min if it's below the range and the max if it's above the range.

https复制: // @ dimo414 //stackoverflow.com/a/42968254/122441

不幸的是,这个版本是截至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 - 限制最小值和最大值之间的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆