[英]How can I return null in Java when the method is defined as int data type?
I've been doing a code where its mandatory to use the data type cannot be void and I don't need to return anything.我一直在做一个代码,它强制使用数据类型不能是无效的,我不需要返回任何东西。
In Java, null
is only a valid value for reference types.在 Java 中,
null
只是引用类型的有效值。 It cannot represent a primitive type such as int
.它不能表示原始类型,例如
int
。 Here are some alternatives to consider:以下是一些可供考虑的替代方案:
OptionalInt
type to represent an int
value that may or may not be present.OptionalInt
类型来表示可能存在或不存在的int
值。 In that case, you would return OptionalInt.empty()
in the case that there is no int
value to return, and OptionalInt.of(x)
to return an int x
.int
值,您将返回OptionalInt.empty()
,而OptionalInt.of(x)
返回int x
。 Note that the caller will need to unwrap the int
value (if it is present) using one of the other methods available on that class.int
值(如果存在)。 This approach is often preferred for new code, as it makes the intention and usage very clear.Integer
.Integer
。 This is a wrapper class for int
values that does allow for null
to be returned.null
用于允许返回 null 的int
值。 In addition, Java's auto-unboxing rules allow it to be used in contexts where an int
value is expected, when the value is not null
.null
时,Java 的自动拆箱规则允许它在需要int
值的上下文中使用。 However, if a null
value is unboxed to an int
value, it will result in a NullPointerException
, so it is important to check for null
before performing operations that would result in unboxing.null
值拆箱为int
值,则会导致NullPointerException
,因此在执行可能导致拆箱的操作之前检查null
非常重要。int
return type, it is common to use a sentinal value to represent an abnormal return.int
返回类型,通常使用一个哨兵值来表示异常返回。 For example, if the normal return values for the method are all non-negative integers, you could use a value such as -1
to represent an absent return value.-1
之类的值来表示不存在的返回值。 This is commonly used in older JDK methods such as String.indexOf()
.String.indexOf()
。Exception
when no valid value can be returned.Exception
是有意义的。 It's only a good idea to use this approach for truly exceptional circumstances, as the runtime cost for throwing exceptions is much higher than normal method returns, and the flow of control can make the code harder to understand.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.