简体   繁体   中英

Simple Java question about references to ArrayList element

Say I have the following code,

LinkedList partials = new LinkedList();
partials.add(new ArrayList());
ArrayList head = partials.element();
head.add("Test");

I want "head" to simply be a copy of the Arraylist that is a result of partials.element(). However, now when I make changes to "head", it is reflected in the Arraylist partials. How do I make a copy of the Arraylist that is the first element of partials such that making changes to the Arraylist won't be reflected in partials?

Two options come to mind:

  • Call the ArrayList constructor which takes another collection - that'll make a copy
  • Call clone() on the ArrayList

Note that both of these will create shallow copies - each list will contain references to the same objects. That's fine if they're immutable (like strings) but if you want to create a deeper copy you'll need to do more work.

Is there any reason you're not using generics, by the way? For example, I would probably use:

LinkedList<ArrayList<String>> partials = new LinkedList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
list.add("Test");

// Create a shallow copy and add a reference to that into the linked list
partials.add(new ArrayList<String>(list));

list.add("Another element");

// Prints 1, because the lists are distinct
System.out.println(partials.element().size());

If nothing should ever change the contents of the lists in the linked list, you may want to look at the immutable collections available in Guava , or wrap your clone using Collections.unmodifiableList . Note that the latter only creates a view on the original list, so you'd still need to perform the clone step first.

actually the code can't compile at line 3 : partials.element() returns an Object (the first element of your LinkedList) and you have to cast it as an ArrayList if you want to use it this way.

I agree you don't need generics to make the code easier to add. You could also define partials and head as List instead of LinkedList & ArrayList. Use interface instead of implementations is a good practice and avoid you to use too much specific method like element() one when you don't need to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM