42
public int pollDecrementHigherKey(int x) {
            int savedKey, savedValue;
            if (this.higherKey(x) == null) {
                return null;  // COMPILE-TIME ERROR
            }
            else if (this.get(this.higherKey(x)) > 1) {        
                savedKey = this.higherKey(x);
                savedValue = this.get(this.higherKey(x)) - 1;
                this.remove(savedKey);
                this.put(savedKey, savedValue);
                return savedKey;
            }
            else {
                savedKey = this.higherKey(x);
                this.remove(savedKey);
                return savedKey;
            }
        }

该方法位于作为 TreeMap 扩展的类中,如果这有什么不同的话……有什么想法为什么我不能在这里返回 null 吗?

4

5 回答 5

64

int是一个原始值,null 不是它可以采用的值。您可以将方法返回类型更改为 return java.lang.Integer,然后您可以返回 null,并且返回 int 的现有代码将自动装箱。

Null 仅分配给引用类型,这意味着引用不指向任何内容。基元不是引用类型,它们是值,因此它们永远不会设置为 null。

使用对象包装器 java.lang.Integer 作为返回值意味着您正在传回一个 Object 并且对象引用可以为 null。

于 2013-06-20T19:07:38.450 回答
3

int是原始数据类型。它不是可以null取值的参考变量。您需要将方法返回类型更改为Integerwrapper class 。

于 2013-06-20T19:14:13.340 回答
1

将您的返回类型更改为 java.lang.Integer 。这样你就可以安全地返回 null

于 2019-09-22T00:01:04.117 回答
0

该类型int是原始类型null,如果要返回null,则不能将签名标记为

public Integer pollDecrementHigherKey(int x) {
    x = 10;

    if (condition) {
        return x; // This is auto-boxing, x will be automatically converted to Integer
    } else if (condition2) {
        return null; // Integer inherits from Object, so it's valid to return null
    } else {
        return new Integer(x); // Create an Integer from the int and then return
    }
    
    return 5; // Also will be autoboxed and converted into Integer
}
于 2013-06-20T19:09:14.053 回答
-2

你真的要返回 null 吗?您可以做的事情可能是用 0 值初始化 savedkey 并将 0 作为空值返回。它可以更简单。

于 2013-06-20T19:14:51.350 回答