CopyOnWriteArrayList - 如何更新堆栈?

时间:2015-07-12 22:36:55

标签: java stack copyonwritearraylist

如果是CopyOnWriteArrayList,只要将一个元素添加到集合中,就会创建一个新对象。

请考虑以下示例:

   private static void copyOnWriteArrayList() {
    List<String> playersUsing2 = new CopyOnWriteArrayList<String>();
    System.out.println("Original hashCode = " + playersUsing2.hashCode());
    playersUsing2.add("a1");
    System.out.println("After a1 hashCode = " + playersUsing2.hashCode() + " size = " + playersUsing2.size());
    addElement(playersUsing2, "a2");
    System.out.println("After b1 from copyOnWriteArrayList hashCode = " + playersUsing2.hashCode() + " size = " + playersUsing2.size());
    playersUsing2.add("b1");
    System.out.println("After b1 hashCode = " + playersUsing2.hashCode() + " size = " + playersUsing2.size());
}

private static void addElement(List<String> playersUsingNew, String value) {
    playersUsingNew.add(value);
    System.out.println("After a2 hashCode = " + playersUsingNew.hashCode() + " size = " + playersUsingNew.size());
}

每次添加元素时,都会创建一个新对象,并且堆栈上的playersUsing2引用将更新为指向该内存位置。可以理解的。

现在,我将playersUsing2传递给另一个方法,因此将创建一个新的堆栈帧,playersUsingNew也将指向相同的内存位置。添加新元素时,将创建一个新对象,playersUsingNew将指向新的内存位置。

但是如何更新第一个堆栈帧playersUsing2以指向最新的内存位置?

我看到java.util.concurrent.CopyOnWriteArrayList.add(E)实施但无法理解。是通过一些本机代码和JVM来处理它是如何发生的?

输出:

Original hashCode = 1
After a1 hashCode = 3087 size = 1
After a2 hashCode = 98754 size = 2
After b1 from copyOnWriteArrayList hashCode = 98754 size = 2
After b1 hashCode = 3064461 size = 3

1 个答案:

答案 0 :(得分:0)

总结哈希代码更改表示新对象的创建是错误的概念.hashCode()返回的值绝不保证是对象的内存地址。