OptionalInt和int之间的区别? [英] Difference between OptionalInt and int?

查看:63
本文介绍了OptionalInt和int之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OptionalInt max = IntStream.of(arr).max();

int maximum = 0;
for (int i : arr) {
     maximum = Math.max(i, maximum);
}

这两种方法均返回最大值. OptionalInt 有什么不同?根据 OptionalInt 的定义,如果存在值,则返回 getAsInt(),但是如果不存在值,则抛出 Exception ./p>

Both these methods return maximum value. What does OptionalInt make a difference? As per the definition of OptionalInt, if value is present it returns getAsInt() but if value is not present, it throws an Exception.

推荐答案

与命令式方法相比,使用流方法的优势在于,当数组 arr 中没有元素时,我们表示最大值缺失,表示缺失值.

The advantage of using the stream approach over the imperative approach is that when there are no elements in the array arr then we represent the maximum value as absent to indicate a missing value.

关于您所说的描述:

根据OptionalInt的定义,如果存在则返回值getasIntValue(),但如果不存在value,则会引发Exception.

As per the definition of OptionalInt,if value if present it returns getasIntValue() but if value is not present ,it throws Exception.

请注意,仅当您调用 getAsInt()直接来自可选结果,其值为不存在.

Note that it throws an exception only when you call getAsInt() directly from an optional result and the value is absent.

从某种意义上说,这是一件好事,当我们尝试使用

This is a good thing in the sense that when we attempt to access the element using getAsInt() as you've mentioned and there is no value present then a NoSuchElementException will be thrown and in-fact getting an exception, in this case, might be useful because you now know there is no value present whereas the imperative approach could lead to hiding a bug because if the array is empty then the maximum value is 0 which is false except in a certain scenario mentioned in my 2nd to last paragraph below.

您所显示的小代码在出现错误时可能很容易修复,但是在生产代码中,由于代码库的大小,可能很难找到它.

Such, small code as you've shown will probably be easy to fix when there is a bug but in production code, it may be hard to find due to the size of the codebase.

如果 0 实际上是要在数组为空时要提供的默认值,则可以按原样进行命令式方法,也可以使用可选方法进行以下操作:

if 0 is, in fact, the default you want to provide when the array is empty then you can proceed with the imperative approach as is or using the optional approach it could be done as:

int max = IntStream.of(arr).max()
                   .orElse(0);

在上述情况下,不会引发 NoSuchElementException 异常.另外,我建议不要使用直接从可选结果中获取getAsInt(),除非您100%确定数组不会为空.而是利用 orElse orElseGet

In the above scenario, the NoSuchElementException exception will not be thrown. Also, I'd recommend not to use getAsInt() straight from an optional result unless you're 100% sure the array will not be empty. rather utilise orElse, orElseGet or orElseThrow depending on which you find most appropriate for the given situation.

这篇关于OptionalInt和int之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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