简体   繁体   English

Java中的Integer.MAX_VALUE

[英]Integer.MAX_VALUE in java

I have read about MAX_VALUE and found that a constant can hold a maximum value of 2^31-1. 我已阅读有关MAX_VALUE的内容,发现一个常数可以容纳2 ^ 31-1的最大值。 Where is the need to use a MAX_VALUE for any program? 在哪里需要对任何程序使用MAX_VALUE?

I am also confused on this piece of stack code, where if the stack is empty it return Integer.Max_VALUE. 我对这段堆栈代码也感到困惑,如果堆栈为空,则返回Integer.Max_VALUE。

if(s2.isEmpty())
    return Integer.MAX_VALUE; 

Why should we return a max number when the stack is empty ? 当堆栈为空时,为什么还要返回一个最大值?

Example usage of MAX_VALUE : MAX_VALUE用法示例:

List<Integer> l = Arrays.asList(1, 2, 182938, 1293);
Integer min = Integer.MAX_VALUE;

for (Integer i : l) { 
     min = Math.min(min, i);
}

To be honest, I have hardly ever used this, but for one thing it is quite practical: 老实说,我几乎没有用过,但有一点很实际:

If you are searching for a minimum, you can inititally start with Integer.MAX_VALUE as it is guaranteed that the next value will be smaller. 如果要搜索最小值,则可以从Integer.MAX_VALUE开始,因为可以保证下一个值会较小。

The second use case scenario is to check if this variable can be used for any further calculations, by checking (var <= Integer.MAX_VALUE - valueToAdd && valueToAdd >= 0) beforehand. 第二个用例场景是通过事先检查(var <= Integer.MAX_VALUE - valueToAdd && valueToAdd >= 0)来检查此变量是否可以用于任何进一步的计算。

Returning Integer.MAX_VALUE is nice if you certainly know that a number cannot possible be that high. 如果您确实知道一个数字不可能那么高,则返回Integer.MAX_VALUE很好。 I often use -1 as return value if an int cannot be negative, but if it can you need to think of something else, which would be using MAX_VALUE then. 如果int不能为负数,我经常使用-1作为返回值,但是如果可以,则需要考虑其他情况,那就是使用MAX_VALUE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM