關於Integer

1. 如何對 List<Integer> result = new ArrayList<>(nums.length) result某個索引值進行修改?

答案是不能,除非通過反射。

原因是Integer中對value 的保存是不可修改的

    private final int value;

2. 如何交換兩個Integer類型的值?

	public static void main(String[] args) {
	    Integer i = 1;
	    Integer j = 2;
	    swap(i, j);
	    System.out.println("i=" + i + "----------j=" + j);
	} 

	private static void swap(Integer i, Integer j) {
	    try {
	        int temp = i;
	        Field field = Integer.class.getDeclaredField("value");
	        field.setAccessible(true);
	        field.set(i, j);
	        field.set(j, temp);
	    } catch (NoSuchFieldException e) {
	        e.printStackTrace();
	    } catch (IllegalAccessException e) {
	        e.printStackTrace();
	    }
	}

以上方式輸出:

i=2----------j=2

而如果

	    Integer i = 128;
	    Integer j = 129;

輸出正確:

i=129----------j=128

原因分析:

Integer 中有Integer 數組緩存,此緩存通過靜態類IntegerCache來實現

static final Integer cache[];
private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        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) {
                try {
                    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);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

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

圖示解釋如下:

3. Practise

Integer testA = 1;
Integer testB = 1;

Integer testC = 128;
Integer testD = 128;
System.out.println("testA=testB " + (testA == testB) + ",\ntestC=testD " + (testC == testD));

輸出:

testA=testB true,
testC=testD false

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章