web-dev-qa-db-ja.com

シグネチャがreturn intを示すメソッドでnullを返しますか?

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を返せない理由はありますか?

34
Ryan Yu

intはプリミティブであり、nullは取り得る値ではありません。メソッドの戻り値の型を変更して、Java.lang.Integerその後、nullを返すことができ、intを返す既存のコードはオートボックス化されます。

ヌルは参照タイプにのみ割り当てられます。つまり、参照は何も指していません。プリミティブは参照型ではなく、値であるため、nullに設定されることはありません。

オブジェクトラッパーJava.lang.Integerを戻り値として使用することは、Objectを返すことを意味し、オブジェクト参照はnullになります。

52
Nathan Hughes

intはプリミティブデータ型です。 null値をとることができる参照変数ではありません。メソッドの戻り値の型をInteger wrapper classに変更する必要があります。

2
NINCOMPOOP

タイプintはプリミティブであり、nullにはできません。nullを返したい場合は、署名をマークしてください

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

        if(condition){
         return x;      // this is autoboxing, x will be automatically converted to Integer
        }else if(condition2){
         return null; // Integer referes to Object, so valid to return null
        }else{
         return new Integer(x); // manually created Integer from int and then return

         }
         return 5; // also will be autoboxed and converted into Integer
  }
0
Prasad Kharkar