在签名为return int的方法中返回null?

Rya*_* Yu 35 java null return

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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

该方法位于一个类,它是TreeMap的扩展,如果这有任何区别......任何想法为什么我不能在这里返回null?

Nat*_*hes 54

int是原始的,null不是它可以承担的值.您可以将方法返回类型更改为return java.lang.Integer,然后您可以返回null,并且返回int的现有代码将自动进行生成.

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

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