【面試題】用unsafe的 setMemory 方法 修改數組

 題目

面試題:int[] a = {1, 2, 3, 4};  用unsafe的 setMemory 方法 修改數組 ,只改後面2個 改成 int[] a = {1, 2, 101058054, 101058054}

實現 

public static void intArray() throws NoSuchFieldException, IllegalAccessException {
    Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
    //Field unsafeField = Unsafe.class.getDeclaredFields()[0]; //也可以這樣,作用相同
    unsafeField.setAccessible(true);
    Unsafe unsafe = (Unsafe) unsafeField.get(null);
    int[] a = {1, 2, 3, 4};
    //arrayBaseOffset方法可以獲取數組中第一個元素的偏移地址,
    int baseOffset = unsafe.arrayBaseOffset(int[].class);
    //使用arrayIndexScale方法可以獲取數組中元素間的偏移地址增量
    int scale = unsafe.arrayIndexScale(int[].class);
    // System.out.println(scale);
    // System.out.println("---------------");
    for (int i = 0; i < a.length; i++) {
        int offset = baseOffset + scale * i;
        //     System.out.println(offset + " : " + unsafe.getInt(a, offset));
        if (i >= 2) {
            //將內存設置爲指定值
            //TODO 用unsafe的 setMemory 方法 修改數組
            //ffset 是偏移量,第三參數是多少個字節被第四個參數填充 
             //在指定內存位置設置值
            unsafe.setMemory(a, offset, 10, (byte) 101058054);
            // System.out.println(offset + " : " + unsafe.getInt(a, offset));
        }
    }
    //int[] b = {1, 2, 101058054, 101058054};
    System.out.println(Arrays.toString(a));
}

 

參考

https://www.mdnice.com/writing/e097354eb4434b78a4322a5dbaab8857

https://blog.csdn.net/u010398771/article/details/85319991

 

 

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