How to change value of ArrayList element in java

前端 未结 7 1907
清酒与你
清酒与你 2020-12-02 09:57

Please help me with below code , I get the same output even after changing the value

import java.util.*;

class Test {
    public static void main(String[] a         


        
7条回答
  •  一个人的身影
    2020-12-02 10:12

    I think the problem is that you think the statement ...

    x = Integer.valueOf(9);
    

    ... causes that the value of '9' get 'stored' into(!) the Object on which x is referencing.

    But thats wrong.

    Instead the statement causes something similar as if you would call

    x = new Integer(9); 
    

    If you have a look to the java source code, you will see what happens in Detail.

    Here is the code of the "valueOf(int i)" method in the "Integer" class:

    public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
    

    and further, whenever the IntegerCache class is used for the first time the following script gets invoked:

    static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            }
            high = h;
    
            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
        }
    

    You see that either a new Integer Object is created with "new Integer(i)" in the valueOf method ... ... or a reference to a Integer Object which is stored in the IntegerCache is returned.

    In both cases x will reference to a new Object.

    And this is why the reference to the Object in your list get lost when you call ...

    x = Integer.valueOf(9);
    

    Instead of doing so, in combination with a ListIterator use ...

    i.set(Integer.valueOf(9));
    

    ... after you got the element you want to change with ...

    i.next();
    

提交回复
热议问题