The linked Integer object does not grow

I am developing a Java application, and now I have noticed strange behavior that confused me. I have the following situation:

    Integer currentIndex = 0;
    doSomethings(currentIndex);
    System.out.println("Print "+currentIndex);


    private void doSomethings(Integer currentIndex){
        //Do other things and update my current index
        currentIndex++;


    }

but always get the value 0. I remember that objects are passed as a reference in java, while primitive types are like copying. Why in this case do I get 0?

+4
source share
7 answers

Integer . , . , Integer int ( "unboxing" ), int . Integer. Integer, , . .

-:

private static void doSomethings(java.lang.Integer);
  Code:
   Stack=2, Locals=1, Args_size=1
   0:   aload_0
   1:   invokevirtual   #56; //Method java/lang/Integer.intValue:()I  --> get the int value of the Integer
   4:   iconst_1 --> constant value 1
   5:   iadd   --> add int value and 1
   6:   invokestatic    #16; //Method java/lang/Integer.valueOf:(I)Ljava/lang/In --> get another integer with value increased by 1
teger;
   9:   astore_0
   10:  return
+8

.

, Java . ++ Java-.

, java , "auto boxing". Integer int .

, :

Interger myInt = 0;
int i = myInt++; // this line

: myInt int, int i. , myInt.

, , ++ , Integer . , Integer , .

+2

, beworker . .

Java . , , currentIndex, , currentIndex dosomething() .

. , Eng.Fouad , .

+1

Java . ( ). , Integer . , .

, , , .

private Integer doSomethings(Integer currentIndex){

            return currentIndex++;   
 }
+1
    currentIndex = doSomethings(currentIndex);
    private Integer doSomethings(Integer currentIndex){
          //Do other things and update my current index
          return currentIndex++;     
    }
0

  Integer currentIndex = 0;
  currentIndex = doSomethings(currentIndex);
  System.out.println("Print "+currentIndex);


  private Integer doSomethings(Integer currentIndex,){
    //Do other things and update my current index
    return currentIndex++;

doSomethings () increments the value of currentIndex and returns it. Then save this object in currentIndex link

Good luck !!!

0
source

Java is passed by value, these two articles explain well

http://www.javaranch.com/campfire/StoryCups.jsp http://www.javaranch.com/campfire/StoryPassBy.jsp

Read in that order.

0
source

All Articles