2017-06-10 9 views
1

Eclipse IDEにJava SE 8アプリケーションを作成しています。私が遭遇した問題は次のとおりです。呼び出し元に影響を与えないメソッドへのパラメータとして渡されるプリミティブラッパークラスのインクリメント

private Object[][] adjustIndexTaskValueAdded(int size){ 
     Integer adjustingIndex = 0; 
     Object[][] tasksDisplay = new Object[size][taskValues[0].length]; 

     for (int i = 0; i < size; i++) {       
      tasksDisplay[i][0] = taskValues[i][0];//phase colour 
      tasksDisplay[i][1] = identifyNextRowIDTaskTable(adjustingIndex, i);// the index 
     } 
     return tasksDisplay; 
} 

だから、私は私がidentifyNextRowIDTaskTable()メソッドに渡すadjustingIndex整数ラッパークラスを持っています。ローカルvarは、子メソッドで変更される値を格納できるようにします。

private String identifyNextRowIDTaskTable(Integer adjustingIndex, int currentRowID){ 
     if(UtilityOperations.isPhaseRow(phaseColourCurrent)){//it's a phase row 
      adjustingIndex++; 
      return ""; 
     } 
     else{//it's a task row 
      int displayID = tableID - adjustingIndex; 
      adjustingIndex = 0; 
      return String.valueOf(displayID);   
     } 
} 

上記の方法は、私が通過整数ラッパークラスを修正する方法を表示します。 私は、アプリケーションを実行すると、新しい値は、呼び出しメソッドで反映されません。子メソッドでは値が変更/調整されますが、親メソッドでは変更が表示されないようです。結局のところ、結果は誤りになります。

表示されるソースコードは簡略化されています...

問題は何ですか? 参照型varを渡しますが、再帰的な操作ではありません。 オブジェクトの状態を使用して、代わりに値を格納することができます。しかし、私は現在の落とし穴を理解したい。

答えて

3

これはintとその値をインクリメントを取得するためにIntegerから値をアンボクシングされ

adjustingIndex++; 

考えてみましょう敬具、これは同等です:

int tmp = adjustingIndex.intValue(); 
tmp++; 
adjustingIndex = Integer.valueOf(tmp); 

これはリセットされますパラメータadjustingIndexは、新しい整数の場合、呼び出し側メソッドの変数adjustingIndexの値は変更されません。これは別の参照です。

もう一度考えてみます。

adjustingIndex = 0; 

は、これも新しい整数に基準となるパラメータadjustingIndexをリセットし、それが呼び出しメソッドでadjustingIndex変数の値を変更しません。

1つの代替は

adjustingIndex.set(0); 

AtomicIntegerAtomicInteger

AtomicInteger adjustingIndex = new AtomicInteger(0); 

増分

adjustingIndex.incrementAndGet(); 

がゼロに戻され使用することで、整数の値を変更する方法を有すること対照的に、Integerは不変であり、その値は変更できません。

関連する問題