对 ArrayList 上内存的对象引用

Object references to memory on an ArrayList

我很难理解这段代码的结果。看一看 我有 ArrayList<Object> mylist = new ArrayList<Object>(); 我知道这个 mylist 在内存中有一个指向 new ArrayList<Object>(); 的指针,但是如果我想重新排列这个 mylist 中的项目然后取出项目怎么办,代码如下所示

//supposing i have 0 to 9 items in my list,giving it a size of 10
Object o = mylist.get(2); // i retrieved the 3rd item
mylist.add(0,o); // i now place it as the first item
mylist.remove(2+1); // i want to now remove the old object. in real life the int
// is gotten somewhere else
o = mylist.get(0); // i am now retrieving the newly placed item

所以我的最后一个问题是我的 o 对象会是我用 Object o = mylist.get(2); 得到的对象吗?如果没有,有人可以指导我如何重新排列我的物品并再次取回吗?

我在想我应该克隆 mylist Arraylist 然后做 get() 这也是合法的吗?

是的,在该代码的末尾,'o' 的值仍将是 myList.get(2)myList.get(2) 指的是堆中的某个对象,当您说 myList.add(0, o) 时,您实际上只是在数组中的索引 0 处添加另一个引用,指向 myList.get() 指向的同一对象。然后您删除了索引 2 处的引用,但索引 0 处的指针仍然存在。