Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

java - Returning null in a method whose signature says return int?

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;
            }
        }

The method lies within a class that is an extension of TreeMap, if that makes any difference... Any ideas why I can't return null here?

question from:https://stackoverflow.com/questions/17221759/returning-null-in-a-method-whose-signature-says-return-int

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

int is a primitive, null is not a value that it can take on. You could change the method return type to return java.lang.Integer and then you can return null, and existing code that returns int will get autoboxed.

Nulls are assigned only to reference types, it means the reference doesn't point to anything. Primitives are not reference types, they are values, so they are never set to null.

Using the object wrapper java.lang.Integer as the return value means you are passing back an Object and the object reference can be null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...