Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如果一个方法必须返回一个对象,并且它有一个返回 null 的选项。但是如果一个函数必须返回一个int,如果int找不到/生成这样的返回值等等,它应该怎么办?即抛出异常?返回一个布尔值?将返回类型从 int 更改为某个数据对象?
int
您可以使用整数包装对象
public Integer returnNull(){ return null; }
不过要小心,因为这将编译然后抛出 NullPointerException
public void myMethod(){ .... int i = returnNull(); .... }
感谢自动装箱。
在您建议的选项中,您不能返回布尔值。抛出异常是干净/java的方法。
返回-1。这是 int 返回最常见的做法