www.webdeveloper.com
Results 1 to 2 of 2

Thread: How to copy ArrayList without copying the references

  1. #1
    Join Date
    Jul 2013
    Posts
    2

    How to copy ArrayList without copying the references

    Hi All,

    I am facing an issue to copy a ArrayList without copying its references.
    Suppose arrayList contains some lineItems present in object.
    Below is the code snippet I used.
    Example:

    List arrayList= new ArrayList();
    arrayList.add(object);

    List newArrayList = new ArrayList();
    newArrayList.addAll(arrayList);

    If I delete any lineItems from the newly created list (newArrayList). Same lineItems are also getting deleted from the main list (arrayList).

    Is there any way to copy the arraylist without the references being copied?
    If itís possible to do so. Could anyone please provide the code snippet.

    Thanks in advance.

    Regards,
    Partho

  2. #2
    Join Date
    Dec 2013
    Posts
    2
    Hello Partho,
    I cannot understand why it doesn't work for you.

    Assumed, we have the following code snippet:
    Code:
    List<Integer> list = new ArrayList<>();
    		list.add(1);
    		list.add(2);
    		list.add(3);
    		List<Integer> duplList = new ArrayList<>();
    		duplList = list;
    		duplList.remove(0);
    		System.out.println(duplList);
    		System.out.println(list);
    The output for both lists is:
    [2, 3]
    which is not what you want.

    However, if I change the code to:
    Code:
    List<Integer> list = new ArrayList<>();
    		list.add(1);
    		list.add(2);
    		list.add(3);
    		List<Integer> duplList = new ArrayList<>();
    		duplList.addAll(list);
    		duplList.remove(0);
    		System.out.println(duplList);
    		System.out.println(list);
    the duplicated list is [2, 3] and the main one [1, 2, 3] which is what you want, right?

    You sure it doesn't work?

    Regards

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles