How to change the value of array elements

前端 未结 7 2026
情歌与酒
情歌与酒 2020-12-21 10:57
int A = 300;
int B = 400;
int C = 1000;
int D = 500;

int []abcd = {A,B,C,D};
Arrays.sort(abcd);   // the sequence of array elements will be {300, 400, 500,1000}
         


        
7条回答
  •  我在风中等你
    2020-12-21 11:18

    First of all, the variables A, B, C and D have no "location in the array". What you did was to create a blank array with 4 slots, and affect the values of those variables in position 0, 1, 2 and 3.

    When you sort the array, the values (once again) get shuffled between the array's slots, but sort() doesn't know anything about the variables A, B, C and D, so their values remain unchanged. If you want those to change, you need to re-affect back the values into the variables, by using each slot's position:

    A = abcd[0];
    B = abcd[1];
    C = abcd[2];
    D = abcd[3];
    

提交回复
热议问题