How to copy a java.util.List into another java.util.List











up vote
99
down vote

favorite
21












I have a List<SomeBean> that is populated from a Web Service. I want to copy/clone the contents of that list into an empty list of the same type. A Google search for copying a list suggested me to use Collections.copy() method. In all the examples I saw, the destination list was supposed to contain the exact number of items for the copying to take place.



As the list I am using is populated through a web service and it contains hundreds of objects, I cannot use the above technique. Or I am using it wrong??!! Anyways, to make it work, I tried to do something like this, but I still got an IndexOutOfBoundsException.



List<SomeBean> wsList = app.allInOne(template);

List<SomeBean> wsListCopy=new ArrayList<SomeBean>(wsList.size());
Collections.copy(wsListCopy,wsList);
System.out.println(wsListCopy.size());


I tried to use the wsListCopy=wsList.subList(0, wsList.size()) but I got a ConcurrentAccessException later in the code. Hit and trial. :)



Anyways, my question is simple, how can I copy the entire content of my list into another List? Not through iteration, of course.










share|improve this question


















  • 11




    Any copy will use iteration of course. You can hide it away but it will still be there.
    – Peter Lawrey
    Jan 14 '13 at 13:55






  • 1




    First of all: are you sure you need to copy that list? What is your motivation in doing that?
    – ppeterka
    Jan 14 '13 at 13:56






  • 2




    Yup, iteration is just hidden under that layers. But the comment was added to to prevent any iteration answers. :)
    – Mono Jamoon
    Jan 14 '13 at 13:56










  • @ppeterka I am performing operations on the list, like removeAll(). This causes the list to loss its original data. And "that data" is also required afterwards.
    – Mono Jamoon
    Jan 14 '13 at 13:59










  • What is the actual type of a list, which is returning by app.allInOne(template)? ArrayList?
    – Andremoniy
    Jan 14 '13 at 14:10















up vote
99
down vote

favorite
21












I have a List<SomeBean> that is populated from a Web Service. I want to copy/clone the contents of that list into an empty list of the same type. A Google search for copying a list suggested me to use Collections.copy() method. In all the examples I saw, the destination list was supposed to contain the exact number of items for the copying to take place.



As the list I am using is populated through a web service and it contains hundreds of objects, I cannot use the above technique. Or I am using it wrong??!! Anyways, to make it work, I tried to do something like this, but I still got an IndexOutOfBoundsException.



List<SomeBean> wsList = app.allInOne(template);

List<SomeBean> wsListCopy=new ArrayList<SomeBean>(wsList.size());
Collections.copy(wsListCopy,wsList);
System.out.println(wsListCopy.size());


I tried to use the wsListCopy=wsList.subList(0, wsList.size()) but I got a ConcurrentAccessException later in the code. Hit and trial. :)



Anyways, my question is simple, how can I copy the entire content of my list into another List? Not through iteration, of course.










share|improve this question


















  • 11




    Any copy will use iteration of course. You can hide it away but it will still be there.
    – Peter Lawrey
    Jan 14 '13 at 13:55






  • 1




    First of all: are you sure you need to copy that list? What is your motivation in doing that?
    – ppeterka
    Jan 14 '13 at 13:56






  • 2




    Yup, iteration is just hidden under that layers. But the comment was added to to prevent any iteration answers. :)
    – Mono Jamoon
    Jan 14 '13 at 13:56










  • @ppeterka I am performing operations on the list, like removeAll(). This causes the list to loss its original data. And "that data" is also required afterwards.
    – Mono Jamoon
    Jan 14 '13 at 13:59










  • What is the actual type of a list, which is returning by app.allInOne(template)? ArrayList?
    – Andremoniy
    Jan 14 '13 at 14:10













up vote
99
down vote

favorite
21









up vote
99
down vote

favorite
21






21





I have a List<SomeBean> that is populated from a Web Service. I want to copy/clone the contents of that list into an empty list of the same type. A Google search for copying a list suggested me to use Collections.copy() method. In all the examples I saw, the destination list was supposed to contain the exact number of items for the copying to take place.



As the list I am using is populated through a web service and it contains hundreds of objects, I cannot use the above technique. Or I am using it wrong??!! Anyways, to make it work, I tried to do something like this, but I still got an IndexOutOfBoundsException.



List<SomeBean> wsList = app.allInOne(template);

List<SomeBean> wsListCopy=new ArrayList<SomeBean>(wsList.size());
Collections.copy(wsListCopy,wsList);
System.out.println(wsListCopy.size());


I tried to use the wsListCopy=wsList.subList(0, wsList.size()) but I got a ConcurrentAccessException later in the code. Hit and trial. :)



Anyways, my question is simple, how can I copy the entire content of my list into another List? Not through iteration, of course.










share|improve this question













I have a List<SomeBean> that is populated from a Web Service. I want to copy/clone the contents of that list into an empty list of the same type. A Google search for copying a list suggested me to use Collections.copy() method. In all the examples I saw, the destination list was supposed to contain the exact number of items for the copying to take place.



As the list I am using is populated through a web service and it contains hundreds of objects, I cannot use the above technique. Or I am using it wrong??!! Anyways, to make it work, I tried to do something like this, but I still got an IndexOutOfBoundsException.



List<SomeBean> wsList = app.allInOne(template);

List<SomeBean> wsListCopy=new ArrayList<SomeBean>(wsList.size());
Collections.copy(wsListCopy,wsList);
System.out.println(wsListCopy.size());


I tried to use the wsListCopy=wsList.subList(0, wsList.size()) but I got a ConcurrentAccessException later in the code. Hit and trial. :)



Anyways, my question is simple, how can I copy the entire content of my list into another List? Not through iteration, of course.







java collections copy






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 14 '13 at 13:52









Mono Jamoon

1,772133454




1,772133454








  • 11




    Any copy will use iteration of course. You can hide it away but it will still be there.
    – Peter Lawrey
    Jan 14 '13 at 13:55






  • 1




    First of all: are you sure you need to copy that list? What is your motivation in doing that?
    – ppeterka
    Jan 14 '13 at 13:56






  • 2




    Yup, iteration is just hidden under that layers. But the comment was added to to prevent any iteration answers. :)
    – Mono Jamoon
    Jan 14 '13 at 13:56










  • @ppeterka I am performing operations on the list, like removeAll(). This causes the list to loss its original data. And "that data" is also required afterwards.
    – Mono Jamoon
    Jan 14 '13 at 13:59










  • What is the actual type of a list, which is returning by app.allInOne(template)? ArrayList?
    – Andremoniy
    Jan 14 '13 at 14:10














  • 11




    Any copy will use iteration of course. You can hide it away but it will still be there.
    – Peter Lawrey
    Jan 14 '13 at 13:55






  • 1




    First of all: are you sure you need to copy that list? What is your motivation in doing that?
    – ppeterka
    Jan 14 '13 at 13:56






  • 2




    Yup, iteration is just hidden under that layers. But the comment was added to to prevent any iteration answers. :)
    – Mono Jamoon
    Jan 14 '13 at 13:56










  • @ppeterka I am performing operations on the list, like removeAll(). This causes the list to loss its original data. And "that data" is also required afterwards.
    – Mono Jamoon
    Jan 14 '13 at 13:59










  • What is the actual type of a list, which is returning by app.allInOne(template)? ArrayList?
    – Andremoniy
    Jan 14 '13 at 14:10








11




11




Any copy will use iteration of course. You can hide it away but it will still be there.
– Peter Lawrey
Jan 14 '13 at 13:55




Any copy will use iteration of course. You can hide it away but it will still be there.
– Peter Lawrey
Jan 14 '13 at 13:55




1




1




First of all: are you sure you need to copy that list? What is your motivation in doing that?
– ppeterka
Jan 14 '13 at 13:56




First of all: are you sure you need to copy that list? What is your motivation in doing that?
– ppeterka
Jan 14 '13 at 13:56




2




2




Yup, iteration is just hidden under that layers. But the comment was added to to prevent any iteration answers. :)
– Mono Jamoon
Jan 14 '13 at 13:56




Yup, iteration is just hidden under that layers. But the comment was added to to prevent any iteration answers. :)
– Mono Jamoon
Jan 14 '13 at 13:56












@ppeterka I am performing operations on the list, like removeAll(). This causes the list to loss its original data. And "that data" is also required afterwards.
– Mono Jamoon
Jan 14 '13 at 13:59




@ppeterka I am performing operations on the list, like removeAll(). This causes the list to loss its original data. And "that data" is also required afterwards.
– Mono Jamoon
Jan 14 '13 at 13:59












What is the actual type of a list, which is returning by app.allInOne(template)? ArrayList?
– Andremoniy
Jan 14 '13 at 14:10




What is the actual type of a list, which is returning by app.allInOne(template)? ArrayList?
– Andremoniy
Jan 14 '13 at 14:10












13 Answers
13






active

oldest

votes

















up vote
187
down vote



accepted










Just use this:



List<SomeBean> newList = new ArrayList<SomeBean>(otherList);


Note: still not thread safe, if you modify otherList from another thread, then you may want to make that otherList (and even newList) a CopyOnWriteArrayList, for instance -- or use a lock primitive, such as ReentrantReadWriteLock to serialize read/write access to whatever lists are concurrently accessed.






share|improve this answer



















  • 1




    Now, I just feel really stupid :) I hope that constructing it like this would not throw any ConcurrentAccessException.
    – Mono Jamoon
    Jan 14 '13 at 13:55






  • 1




    Javadoc: docs.oracle.com/javase/1.4.2/docs/api/java/util/…
    – lcguida
    Jan 14 '13 at 13:55






  • 5




    +1 if he is getting ConcurrentModifcationException, he has a concurrency issue he needs to fix first.
    – Peter Lawrey
    Jan 14 '13 at 13:55








  • 3




    Why is this answer getting so many points if the question mentioned "copy/clone"? This, as long as some other answers have nothing to do with cloning. The same references will be kept for the objects inside the collections whatever collection/stream specific utility-methods you use.
    – yuranos87
    Oct 9 '16 at 21:05






  • 3




    The answer is wrong. The content is not copied. Only It's references.
    – The incredible Jan
    Apr 27 at 11:03


















up vote
23
down vote













This is a really nice Java 8 way to do it:



List<String> list2 = list1.stream().collect(Collectors.toList());


Of course the advantage here is that you can filter and skip to only copy of part of the list.



e.g.



//don't copy the first element 
List<String> list2 = list1.stream().skip(1).collect(Collectors.toList());





share|improve this answer



















  • 4




    is the resulting list a deep-copy or shallow copy of the original list?
    – Ad Infinitum
    Aug 16 '16 at 12:24






  • 6




    A shallow copy.
    – kap
    Nov 29 '16 at 8:57






  • 3




    This, sadly, also is not thread safe. Assuming list is changed while the collector is running, a ConcurrentModificationException is thrown.
    – C-Otto
    Mar 13 '17 at 18:39










  • @Dan, How to skip copying the last element?
    – chandresh
    May 31 '17 at 6:46










  • @chandresh to skip copying the last element, you would just use .limit(list1.size() - 1)
    – Matthew Carpenter
    Jun 26 at 15:04


















up vote
7
down vote














I tried to do something like this, but I still got an IndexOutOfBoundsException.



I got a ConcurrentAccessException




This means you are modifying the list while you are trying to copy it, most likely in another thread. To fix this you have to either




  • use a collection which is designed for concurrent access.


  • lock the collection appropriately so you can iterate over it (or allow you to call a method which does this for you)


  • find a away to avoid needing to copy the original list.







share|improve this answer




























    up vote
    6
    down vote













    originalArrayList.addAll(copyArrayofList);


    Please keep on mind whenever using the addAll() method for copy, the contents of both the array lists (originalArrayList and copyArrayofList) references to the same objects will be added to the list so if you modify any one of them then copyArrayofList also will also reflect the same change.



    If you don't want side effect then you need to copy each of element from the originalArrayList to the copyArrayofList, like using a for or while loop.






    share|improve this answer

















    • 1




      This is one of the few true Answers here, as it specifies #addAll makes a shallow copy, as well as how to deep copy. More details: stackoverflow.com/questions/715650/…
      – cellepo
      Aug 12 at 4:14












    • nice point regarding shallow copy.
      – sunil
      Oct 29 at 5:57


















    up vote
    1
    down vote













    I was having the same problem ConcurrentAccessException and mysolution was to:



    List<SomeBean> tempList = new ArrayList<>();

    for (CartItem item : prodList) {
    tempList.add(item);
    }
    prodList.clear();
    prodList = new ArrayList<>(tempList);


    So it works only one operation at the time and avoids the Exeption...






    share|improve this answer




























      up vote
      1
      down vote













      I tried something similar and was able to reproduce the problem (IndexOutOfBoundsException). Below are my findings:



      1) The implementation of the Collections.copy(destList, sourceList) first checks the size of the destination list by calling the size() method. Since the call to the size() method will always return the number of elements in the list (0 in this case), the constructor ArrayList(capacity) ensures only the initial capacity of the backing array and this does not have any relation to the size of the list. Hence we always get IndexOutOfBoundsException.



      2) A relatively simple way is to use the constructor that takes a collection as its argument:



      List<SomeBean> wsListCopy=new ArrayList<SomeBean>(wsList);  





      share|improve this answer






























        up vote
        1
        down vote













        There is another method with Java 8 in a null-safe way.



        List<SomeBean> wsListCopy = Optional.ofNullable(wsList)
        .map(List::stream)
        .orElseGet(Stream::empty)
        .collect(Collectors.toList());


        If you want to skip one element.



        List<SomeBean> wsListCopy = Optional.ofNullable(wsList)
        .map(List::stream)
        .orElseGet(Stream::empty)
        .skip(1)
        .collect(Collectors.toList());





        share|improve this answer




























          up vote
          1
          down vote













          In Java 10:



          List<T> newList = List.copyOf(oldList);


          List.copyOf() returns an unmodifiable List containing the elements of the given Collection.



           The given Collection must not be null, and it must not contain any null elements.






          share|improve this answer






























            up vote
            0
            down vote













            re: indexOutOfBoundsException, your sublist args are the problem; you need to end the sublist at size-1. Being zero-based, the last element of a list is always size-1, there is no element in the size position, hence the error.






            share|improve this answer






























              up vote
              0
              down vote













              You can use addAll().



              eg : wsListCopy.addAll(wsList);






              share|improve this answer




























                up vote
                0
                down vote













                I can't see any correct answer. If you want a deep copy you have to iterate and copy object manually (you could use a copy constructor).






                share|improve this answer





















                • This is one of the few true Answers here. More details: stackoverflow.com/questions/715650/…
                  – cellepo
                  Aug 12 at 4:16


















                up vote
                0
                down vote













                If you do not want changes in one list to effect another list try this.It worked for me
                Hope this helps.



                  public class MainClass {
                public static void main(String a) {

                List list = new ArrayList();
                list.add("A");

                List list2 = ((List) ((ArrayList) list).clone());

                System.out.println(list);
                System.out.println(list2);

                list.clear();

                System.out.println(list);
                System.out.println(list2);
                }
                }

                > Output:
                [A]
                [A]

                [A]





                share|improve this answer




























                  up vote
                  -2
                  down vote













                  subList function is a trick, the returned object is still in the original list.
                  so if you do any operation in subList, it will cause the concurrent exception in your code, no matter it is single thread or multi thread.






                  share|improve this answer





















                    Your Answer






                    StackExchange.ifUsing("editor", function () {
                    StackExchange.using("externalEditor", function () {
                    StackExchange.using("snippets", function () {
                    StackExchange.snippets.init();
                    });
                    });
                    }, "code-snippets");

                    StackExchange.ready(function() {
                    var channelOptions = {
                    tags: "".split(" "),
                    id: "1"
                    };
                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                    StackExchange.using("externalEditor", function() {
                    // Have to fire editor after snippets, if snippets enabled
                    if (StackExchange.settings.snippets.snippetsEnabled) {
                    StackExchange.using("snippets", function() {
                    createEditor();
                    });
                    }
                    else {
                    createEditor();
                    }
                    });

                    function createEditor() {
                    StackExchange.prepareEditor({
                    heartbeatType: 'answer',
                    convertImagesToLinks: true,
                    noModals: true,
                    showLowRepImageUploadWarning: true,
                    reputationToPostImages: 10,
                    bindNavPrevention: true,
                    postfix: "",
                    imageUploader: {
                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                    allowUrls: true
                    },
                    onDemand: true,
                    discardSelector: ".discard-answer"
                    ,immediatelyShowMarkdownHelp:true
                    });


                    }
                    });














                     

                    draft saved


                    draft discarded


















                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14319732%2fhow-to-copy-a-java-util-list-into-another-java-util-list%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    13 Answers
                    13






                    active

                    oldest

                    votes








                    13 Answers
                    13






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes








                    up vote
                    187
                    down vote



                    accepted










                    Just use this:



                    List<SomeBean> newList = new ArrayList<SomeBean>(otherList);


                    Note: still not thread safe, if you modify otherList from another thread, then you may want to make that otherList (and even newList) a CopyOnWriteArrayList, for instance -- or use a lock primitive, such as ReentrantReadWriteLock to serialize read/write access to whatever lists are concurrently accessed.






                    share|improve this answer



















                    • 1




                      Now, I just feel really stupid :) I hope that constructing it like this would not throw any ConcurrentAccessException.
                      – Mono Jamoon
                      Jan 14 '13 at 13:55






                    • 1




                      Javadoc: docs.oracle.com/javase/1.4.2/docs/api/java/util/…
                      – lcguida
                      Jan 14 '13 at 13:55






                    • 5




                      +1 if he is getting ConcurrentModifcationException, he has a concurrency issue he needs to fix first.
                      – Peter Lawrey
                      Jan 14 '13 at 13:55








                    • 3




                      Why is this answer getting so many points if the question mentioned "copy/clone"? This, as long as some other answers have nothing to do with cloning. The same references will be kept for the objects inside the collections whatever collection/stream specific utility-methods you use.
                      – yuranos87
                      Oct 9 '16 at 21:05






                    • 3




                      The answer is wrong. The content is not copied. Only It's references.
                      – The incredible Jan
                      Apr 27 at 11:03















                    up vote
                    187
                    down vote



                    accepted










                    Just use this:



                    List<SomeBean> newList = new ArrayList<SomeBean>(otherList);


                    Note: still not thread safe, if you modify otherList from another thread, then you may want to make that otherList (and even newList) a CopyOnWriteArrayList, for instance -- or use a lock primitive, such as ReentrantReadWriteLock to serialize read/write access to whatever lists are concurrently accessed.






                    share|improve this answer



















                    • 1




                      Now, I just feel really stupid :) I hope that constructing it like this would not throw any ConcurrentAccessException.
                      – Mono Jamoon
                      Jan 14 '13 at 13:55






                    • 1




                      Javadoc: docs.oracle.com/javase/1.4.2/docs/api/java/util/…
                      – lcguida
                      Jan 14 '13 at 13:55






                    • 5




                      +1 if he is getting ConcurrentModifcationException, he has a concurrency issue he needs to fix first.
                      – Peter Lawrey
                      Jan 14 '13 at 13:55








                    • 3




                      Why is this answer getting so many points if the question mentioned "copy/clone"? This, as long as some other answers have nothing to do with cloning. The same references will be kept for the objects inside the collections whatever collection/stream specific utility-methods you use.
                      – yuranos87
                      Oct 9 '16 at 21:05






                    • 3




                      The answer is wrong. The content is not copied. Only It's references.
                      – The incredible Jan
                      Apr 27 at 11:03













                    up vote
                    187
                    down vote



                    accepted







                    up vote
                    187
                    down vote



                    accepted






                    Just use this:



                    List<SomeBean> newList = new ArrayList<SomeBean>(otherList);


                    Note: still not thread safe, if you modify otherList from another thread, then you may want to make that otherList (and even newList) a CopyOnWriteArrayList, for instance -- or use a lock primitive, such as ReentrantReadWriteLock to serialize read/write access to whatever lists are concurrently accessed.






                    share|improve this answer














                    Just use this:



                    List<SomeBean> newList = new ArrayList<SomeBean>(otherList);


                    Note: still not thread safe, if you modify otherList from another thread, then you may want to make that otherList (and even newList) a CopyOnWriteArrayList, for instance -- or use a lock primitive, such as ReentrantReadWriteLock to serialize read/write access to whatever lists are concurrently accessed.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Feb 11 '15 at 16:24

























                    answered Jan 14 '13 at 13:53









                    fge

                    87.6k16184269




                    87.6k16184269








                    • 1




                      Now, I just feel really stupid :) I hope that constructing it like this would not throw any ConcurrentAccessException.
                      – Mono Jamoon
                      Jan 14 '13 at 13:55






                    • 1




                      Javadoc: docs.oracle.com/javase/1.4.2/docs/api/java/util/…
                      – lcguida
                      Jan 14 '13 at 13:55






                    • 5




                      +1 if he is getting ConcurrentModifcationException, he has a concurrency issue he needs to fix first.
                      – Peter Lawrey
                      Jan 14 '13 at 13:55








                    • 3




                      Why is this answer getting so many points if the question mentioned "copy/clone"? This, as long as some other answers have nothing to do with cloning. The same references will be kept for the objects inside the collections whatever collection/stream specific utility-methods you use.
                      – yuranos87
                      Oct 9 '16 at 21:05






                    • 3




                      The answer is wrong. The content is not copied. Only It's references.
                      – The incredible Jan
                      Apr 27 at 11:03














                    • 1




                      Now, I just feel really stupid :) I hope that constructing it like this would not throw any ConcurrentAccessException.
                      – Mono Jamoon
                      Jan 14 '13 at 13:55






                    • 1




                      Javadoc: docs.oracle.com/javase/1.4.2/docs/api/java/util/…
                      – lcguida
                      Jan 14 '13 at 13:55






                    • 5




                      +1 if he is getting ConcurrentModifcationException, he has a concurrency issue he needs to fix first.
                      – Peter Lawrey
                      Jan 14 '13 at 13:55








                    • 3




                      Why is this answer getting so many points if the question mentioned "copy/clone"? This, as long as some other answers have nothing to do with cloning. The same references will be kept for the objects inside the collections whatever collection/stream specific utility-methods you use.
                      – yuranos87
                      Oct 9 '16 at 21:05






                    • 3




                      The answer is wrong. The content is not copied. Only It's references.
                      – The incredible Jan
                      Apr 27 at 11:03








                    1




                    1




                    Now, I just feel really stupid :) I hope that constructing it like this would not throw any ConcurrentAccessException.
                    – Mono Jamoon
                    Jan 14 '13 at 13:55




                    Now, I just feel really stupid :) I hope that constructing it like this would not throw any ConcurrentAccessException.
                    – Mono Jamoon
                    Jan 14 '13 at 13:55




                    1




                    1




                    Javadoc: docs.oracle.com/javase/1.4.2/docs/api/java/util/…
                    – lcguida
                    Jan 14 '13 at 13:55




                    Javadoc: docs.oracle.com/javase/1.4.2/docs/api/java/util/…
                    – lcguida
                    Jan 14 '13 at 13:55




                    5




                    5




                    +1 if he is getting ConcurrentModifcationException, he has a concurrency issue he needs to fix first.
                    – Peter Lawrey
                    Jan 14 '13 at 13:55






                    +1 if he is getting ConcurrentModifcationException, he has a concurrency issue he needs to fix first.
                    – Peter Lawrey
                    Jan 14 '13 at 13:55






                    3




                    3




                    Why is this answer getting so many points if the question mentioned "copy/clone"? This, as long as some other answers have nothing to do with cloning. The same references will be kept for the objects inside the collections whatever collection/stream specific utility-methods you use.
                    – yuranos87
                    Oct 9 '16 at 21:05




                    Why is this answer getting so many points if the question mentioned "copy/clone"? This, as long as some other answers have nothing to do with cloning. The same references will be kept for the objects inside the collections whatever collection/stream specific utility-methods you use.
                    – yuranos87
                    Oct 9 '16 at 21:05




                    3




                    3




                    The answer is wrong. The content is not copied. Only It's references.
                    – The incredible Jan
                    Apr 27 at 11:03




                    The answer is wrong. The content is not copied. Only It's references.
                    – The incredible Jan
                    Apr 27 at 11:03












                    up vote
                    23
                    down vote













                    This is a really nice Java 8 way to do it:



                    List<String> list2 = list1.stream().collect(Collectors.toList());


                    Of course the advantage here is that you can filter and skip to only copy of part of the list.



                    e.g.



                    //don't copy the first element 
                    List<String> list2 = list1.stream().skip(1).collect(Collectors.toList());





                    share|improve this answer



















                    • 4




                      is the resulting list a deep-copy or shallow copy of the original list?
                      – Ad Infinitum
                      Aug 16 '16 at 12:24






                    • 6




                      A shallow copy.
                      – kap
                      Nov 29 '16 at 8:57






                    • 3




                      This, sadly, also is not thread safe. Assuming list is changed while the collector is running, a ConcurrentModificationException is thrown.
                      – C-Otto
                      Mar 13 '17 at 18:39










                    • @Dan, How to skip copying the last element?
                      – chandresh
                      May 31 '17 at 6:46










                    • @chandresh to skip copying the last element, you would just use .limit(list1.size() - 1)
                      – Matthew Carpenter
                      Jun 26 at 15:04















                    up vote
                    23
                    down vote













                    This is a really nice Java 8 way to do it:



                    List<String> list2 = list1.stream().collect(Collectors.toList());


                    Of course the advantage here is that you can filter and skip to only copy of part of the list.



                    e.g.



                    //don't copy the first element 
                    List<String> list2 = list1.stream().skip(1).collect(Collectors.toList());





                    share|improve this answer



















                    • 4




                      is the resulting list a deep-copy or shallow copy of the original list?
                      – Ad Infinitum
                      Aug 16 '16 at 12:24






                    • 6




                      A shallow copy.
                      – kap
                      Nov 29 '16 at 8:57






                    • 3




                      This, sadly, also is not thread safe. Assuming list is changed while the collector is running, a ConcurrentModificationException is thrown.
                      – C-Otto
                      Mar 13 '17 at 18:39










                    • @Dan, How to skip copying the last element?
                      – chandresh
                      May 31 '17 at 6:46










                    • @chandresh to skip copying the last element, you would just use .limit(list1.size() - 1)
                      – Matthew Carpenter
                      Jun 26 at 15:04













                    up vote
                    23
                    down vote










                    up vote
                    23
                    down vote









                    This is a really nice Java 8 way to do it:



                    List<String> list2 = list1.stream().collect(Collectors.toList());


                    Of course the advantage here is that you can filter and skip to only copy of part of the list.



                    e.g.



                    //don't copy the first element 
                    List<String> list2 = list1.stream().skip(1).collect(Collectors.toList());





                    share|improve this answer














                    This is a really nice Java 8 way to do it:



                    List<String> list2 = list1.stream().collect(Collectors.toList());


                    Of course the advantage here is that you can filter and skip to only copy of part of the list.



                    e.g.



                    //don't copy the first element 
                    List<String> list2 = list1.stream().skip(1).collect(Collectors.toList());






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Dec 16 '15 at 12:35









                    Apostolos

                    3,32331428




                    3,32331428










                    answered Dec 10 '15 at 12:36









                    Dan

                    4,403124261




                    4,403124261








                    • 4




                      is the resulting list a deep-copy or shallow copy of the original list?
                      – Ad Infinitum
                      Aug 16 '16 at 12:24






                    • 6




                      A shallow copy.
                      – kap
                      Nov 29 '16 at 8:57






                    • 3




                      This, sadly, also is not thread safe. Assuming list is changed while the collector is running, a ConcurrentModificationException is thrown.
                      – C-Otto
                      Mar 13 '17 at 18:39










                    • @Dan, How to skip copying the last element?
                      – chandresh
                      May 31 '17 at 6:46










                    • @chandresh to skip copying the last element, you would just use .limit(list1.size() - 1)
                      – Matthew Carpenter
                      Jun 26 at 15:04














                    • 4




                      is the resulting list a deep-copy or shallow copy of the original list?
                      – Ad Infinitum
                      Aug 16 '16 at 12:24






                    • 6




                      A shallow copy.
                      – kap
                      Nov 29 '16 at 8:57






                    • 3




                      This, sadly, also is not thread safe. Assuming list is changed while the collector is running, a ConcurrentModificationException is thrown.
                      – C-Otto
                      Mar 13 '17 at 18:39










                    • @Dan, How to skip copying the last element?
                      – chandresh
                      May 31 '17 at 6:46










                    • @chandresh to skip copying the last element, you would just use .limit(list1.size() - 1)
                      – Matthew Carpenter
                      Jun 26 at 15:04








                    4




                    4




                    is the resulting list a deep-copy or shallow copy of the original list?
                    – Ad Infinitum
                    Aug 16 '16 at 12:24




                    is the resulting list a deep-copy or shallow copy of the original list?
                    – Ad Infinitum
                    Aug 16 '16 at 12:24




                    6




                    6




                    A shallow copy.
                    – kap
                    Nov 29 '16 at 8:57




                    A shallow copy.
                    – kap
                    Nov 29 '16 at 8:57




                    3




                    3




                    This, sadly, also is not thread safe. Assuming list is changed while the collector is running, a ConcurrentModificationException is thrown.
                    – C-Otto
                    Mar 13 '17 at 18:39




                    This, sadly, also is not thread safe. Assuming list is changed while the collector is running, a ConcurrentModificationException is thrown.
                    – C-Otto
                    Mar 13 '17 at 18:39












                    @Dan, How to skip copying the last element?
                    – chandresh
                    May 31 '17 at 6:46




                    @Dan, How to skip copying the last element?
                    – chandresh
                    May 31 '17 at 6:46












                    @chandresh to skip copying the last element, you would just use .limit(list1.size() - 1)
                    – Matthew Carpenter
                    Jun 26 at 15:04




                    @chandresh to skip copying the last element, you would just use .limit(list1.size() - 1)
                    – Matthew Carpenter
                    Jun 26 at 15:04










                    up vote
                    7
                    down vote














                    I tried to do something like this, but I still got an IndexOutOfBoundsException.



                    I got a ConcurrentAccessException




                    This means you are modifying the list while you are trying to copy it, most likely in another thread. To fix this you have to either




                    • use a collection which is designed for concurrent access.


                    • lock the collection appropriately so you can iterate over it (or allow you to call a method which does this for you)


                    • find a away to avoid needing to copy the original list.







                    share|improve this answer

























                      up vote
                      7
                      down vote














                      I tried to do something like this, but I still got an IndexOutOfBoundsException.



                      I got a ConcurrentAccessException




                      This means you are modifying the list while you are trying to copy it, most likely in another thread. To fix this you have to either




                      • use a collection which is designed for concurrent access.


                      • lock the collection appropriately so you can iterate over it (or allow you to call a method which does this for you)


                      • find a away to avoid needing to copy the original list.







                      share|improve this answer























                        up vote
                        7
                        down vote










                        up vote
                        7
                        down vote










                        I tried to do something like this, but I still got an IndexOutOfBoundsException.



                        I got a ConcurrentAccessException




                        This means you are modifying the list while you are trying to copy it, most likely in another thread. To fix this you have to either




                        • use a collection which is designed for concurrent access.


                        • lock the collection appropriately so you can iterate over it (or allow you to call a method which does this for you)


                        • find a away to avoid needing to copy the original list.







                        share|improve this answer













                        I tried to do something like this, but I still got an IndexOutOfBoundsException.



                        I got a ConcurrentAccessException




                        This means you are modifying the list while you are trying to copy it, most likely in another thread. To fix this you have to either




                        • use a collection which is designed for concurrent access.


                        • lock the collection appropriately so you can iterate over it (or allow you to call a method which does this for you)


                        • find a away to avoid needing to copy the original list.








                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jan 14 '13 at 13:58









                        Peter Lawrey

                        436k55549947




                        436k55549947






















                            up vote
                            6
                            down vote













                            originalArrayList.addAll(copyArrayofList);


                            Please keep on mind whenever using the addAll() method for copy, the contents of both the array lists (originalArrayList and copyArrayofList) references to the same objects will be added to the list so if you modify any one of them then copyArrayofList also will also reflect the same change.



                            If you don't want side effect then you need to copy each of element from the originalArrayList to the copyArrayofList, like using a for or while loop.






                            share|improve this answer

















                            • 1




                              This is one of the few true Answers here, as it specifies #addAll makes a shallow copy, as well as how to deep copy. More details: stackoverflow.com/questions/715650/…
                              – cellepo
                              Aug 12 at 4:14












                            • nice point regarding shallow copy.
                              – sunil
                              Oct 29 at 5:57















                            up vote
                            6
                            down vote













                            originalArrayList.addAll(copyArrayofList);


                            Please keep on mind whenever using the addAll() method for copy, the contents of both the array lists (originalArrayList and copyArrayofList) references to the same objects will be added to the list so if you modify any one of them then copyArrayofList also will also reflect the same change.



                            If you don't want side effect then you need to copy each of element from the originalArrayList to the copyArrayofList, like using a for or while loop.






                            share|improve this answer

















                            • 1




                              This is one of the few true Answers here, as it specifies #addAll makes a shallow copy, as well as how to deep copy. More details: stackoverflow.com/questions/715650/…
                              – cellepo
                              Aug 12 at 4:14












                            • nice point regarding shallow copy.
                              – sunil
                              Oct 29 at 5:57













                            up vote
                            6
                            down vote










                            up vote
                            6
                            down vote









                            originalArrayList.addAll(copyArrayofList);


                            Please keep on mind whenever using the addAll() method for copy, the contents of both the array lists (originalArrayList and copyArrayofList) references to the same objects will be added to the list so if you modify any one of them then copyArrayofList also will also reflect the same change.



                            If you don't want side effect then you need to copy each of element from the originalArrayList to the copyArrayofList, like using a for or while loop.






                            share|improve this answer












                            originalArrayList.addAll(copyArrayofList);


                            Please keep on mind whenever using the addAll() method for copy, the contents of both the array lists (originalArrayList and copyArrayofList) references to the same objects will be added to the list so if you modify any one of them then copyArrayofList also will also reflect the same change.



                            If you don't want side effect then you need to copy each of element from the originalArrayList to the copyArrayofList, like using a for or while loop.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Apr 4 '16 at 10:26









                            Divyesh Kanzariya

                            1,87422427




                            1,87422427








                            • 1




                              This is one of the few true Answers here, as it specifies #addAll makes a shallow copy, as well as how to deep copy. More details: stackoverflow.com/questions/715650/…
                              – cellepo
                              Aug 12 at 4:14












                            • nice point regarding shallow copy.
                              – sunil
                              Oct 29 at 5:57














                            • 1




                              This is one of the few true Answers here, as it specifies #addAll makes a shallow copy, as well as how to deep copy. More details: stackoverflow.com/questions/715650/…
                              – cellepo
                              Aug 12 at 4:14












                            • nice point regarding shallow copy.
                              – sunil
                              Oct 29 at 5:57








                            1




                            1




                            This is one of the few true Answers here, as it specifies #addAll makes a shallow copy, as well as how to deep copy. More details: stackoverflow.com/questions/715650/…
                            – cellepo
                            Aug 12 at 4:14






                            This is one of the few true Answers here, as it specifies #addAll makes a shallow copy, as well as how to deep copy. More details: stackoverflow.com/questions/715650/…
                            – cellepo
                            Aug 12 at 4:14














                            nice point regarding shallow copy.
                            – sunil
                            Oct 29 at 5:57




                            nice point regarding shallow copy.
                            – sunil
                            Oct 29 at 5:57










                            up vote
                            1
                            down vote













                            I was having the same problem ConcurrentAccessException and mysolution was to:



                            List<SomeBean> tempList = new ArrayList<>();

                            for (CartItem item : prodList) {
                            tempList.add(item);
                            }
                            prodList.clear();
                            prodList = new ArrayList<>(tempList);


                            So it works only one operation at the time and avoids the Exeption...






                            share|improve this answer

























                              up vote
                              1
                              down vote













                              I was having the same problem ConcurrentAccessException and mysolution was to:



                              List<SomeBean> tempList = new ArrayList<>();

                              for (CartItem item : prodList) {
                              tempList.add(item);
                              }
                              prodList.clear();
                              prodList = new ArrayList<>(tempList);


                              So it works only one operation at the time and avoids the Exeption...






                              share|improve this answer























                                up vote
                                1
                                down vote










                                up vote
                                1
                                down vote









                                I was having the same problem ConcurrentAccessException and mysolution was to:



                                List<SomeBean> tempList = new ArrayList<>();

                                for (CartItem item : prodList) {
                                tempList.add(item);
                                }
                                prodList.clear();
                                prodList = new ArrayList<>(tempList);


                                So it works only one operation at the time and avoids the Exeption...






                                share|improve this answer












                                I was having the same problem ConcurrentAccessException and mysolution was to:



                                List<SomeBean> tempList = new ArrayList<>();

                                for (CartItem item : prodList) {
                                tempList.add(item);
                                }
                                prodList.clear();
                                prodList = new ArrayList<>(tempList);


                                So it works only one operation at the time and avoids the Exeption...







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Oct 16 '15 at 4:24









                                T04435

                                1,6451525




                                1,6451525






















                                    up vote
                                    1
                                    down vote













                                    I tried something similar and was able to reproduce the problem (IndexOutOfBoundsException). Below are my findings:



                                    1) The implementation of the Collections.copy(destList, sourceList) first checks the size of the destination list by calling the size() method. Since the call to the size() method will always return the number of elements in the list (0 in this case), the constructor ArrayList(capacity) ensures only the initial capacity of the backing array and this does not have any relation to the size of the list. Hence we always get IndexOutOfBoundsException.



                                    2) A relatively simple way is to use the constructor that takes a collection as its argument:



                                    List<SomeBean> wsListCopy=new ArrayList<SomeBean>(wsList);  





                                    share|improve this answer



























                                      up vote
                                      1
                                      down vote













                                      I tried something similar and was able to reproduce the problem (IndexOutOfBoundsException). Below are my findings:



                                      1) The implementation of the Collections.copy(destList, sourceList) first checks the size of the destination list by calling the size() method. Since the call to the size() method will always return the number of elements in the list (0 in this case), the constructor ArrayList(capacity) ensures only the initial capacity of the backing array and this does not have any relation to the size of the list. Hence we always get IndexOutOfBoundsException.



                                      2) A relatively simple way is to use the constructor that takes a collection as its argument:



                                      List<SomeBean> wsListCopy=new ArrayList<SomeBean>(wsList);  





                                      share|improve this answer

























                                        up vote
                                        1
                                        down vote










                                        up vote
                                        1
                                        down vote









                                        I tried something similar and was able to reproduce the problem (IndexOutOfBoundsException). Below are my findings:



                                        1) The implementation of the Collections.copy(destList, sourceList) first checks the size of the destination list by calling the size() method. Since the call to the size() method will always return the number of elements in the list (0 in this case), the constructor ArrayList(capacity) ensures only the initial capacity of the backing array and this does not have any relation to the size of the list. Hence we always get IndexOutOfBoundsException.



                                        2) A relatively simple way is to use the constructor that takes a collection as its argument:



                                        List<SomeBean> wsListCopy=new ArrayList<SomeBean>(wsList);  





                                        share|improve this answer














                                        I tried something similar and was able to reproduce the problem (IndexOutOfBoundsException). Below are my findings:



                                        1) The implementation of the Collections.copy(destList, sourceList) first checks the size of the destination list by calling the size() method. Since the call to the size() method will always return the number of elements in the list (0 in this case), the constructor ArrayList(capacity) ensures only the initial capacity of the backing array and this does not have any relation to the size of the list. Hence we always get IndexOutOfBoundsException.



                                        2) A relatively simple way is to use the constructor that takes a collection as its argument:



                                        List<SomeBean> wsListCopy=new ArrayList<SomeBean>(wsList);  






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Feb 3 '16 at 23:47









                                        Brian Beinlich

                                        35




                                        35










                                        answered Jan 14 '13 at 19:54









                                        Abhay Yadav

                                        635




                                        635






















                                            up vote
                                            1
                                            down vote













                                            There is another method with Java 8 in a null-safe way.



                                            List<SomeBean> wsListCopy = Optional.ofNullable(wsList)
                                            .map(List::stream)
                                            .orElseGet(Stream::empty)
                                            .collect(Collectors.toList());


                                            If you want to skip one element.



                                            List<SomeBean> wsListCopy = Optional.ofNullable(wsList)
                                            .map(List::stream)
                                            .orElseGet(Stream::empty)
                                            .skip(1)
                                            .collect(Collectors.toList());





                                            share|improve this answer

























                                              up vote
                                              1
                                              down vote













                                              There is another method with Java 8 in a null-safe way.



                                              List<SomeBean> wsListCopy = Optional.ofNullable(wsList)
                                              .map(List::stream)
                                              .orElseGet(Stream::empty)
                                              .collect(Collectors.toList());


                                              If you want to skip one element.



                                              List<SomeBean> wsListCopy = Optional.ofNullable(wsList)
                                              .map(List::stream)
                                              .orElseGet(Stream::empty)
                                              .skip(1)
                                              .collect(Collectors.toList());





                                              share|improve this answer























                                                up vote
                                                1
                                                down vote










                                                up vote
                                                1
                                                down vote









                                                There is another method with Java 8 in a null-safe way.



                                                List<SomeBean> wsListCopy = Optional.ofNullable(wsList)
                                                .map(List::stream)
                                                .orElseGet(Stream::empty)
                                                .collect(Collectors.toList());


                                                If you want to skip one element.



                                                List<SomeBean> wsListCopy = Optional.ofNullable(wsList)
                                                .map(List::stream)
                                                .orElseGet(Stream::empty)
                                                .skip(1)
                                                .collect(Collectors.toList());





                                                share|improve this answer












                                                There is another method with Java 8 in a null-safe way.



                                                List<SomeBean> wsListCopy = Optional.ofNullable(wsList)
                                                .map(List::stream)
                                                .orElseGet(Stream::empty)
                                                .collect(Collectors.toList());


                                                If you want to skip one element.



                                                List<SomeBean> wsListCopy = Optional.ofNullable(wsList)
                                                .map(List::stream)
                                                .orElseGet(Stream::empty)
                                                .skip(1)
                                                .collect(Collectors.toList());






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Dec 14 '17 at 12:32









                                                Nicolas Henneaux

                                                5,10542647




                                                5,10542647






















                                                    up vote
                                                    1
                                                    down vote













                                                    In Java 10:



                                                    List<T> newList = List.copyOf(oldList);


                                                    List.copyOf() returns an unmodifiable List containing the elements of the given Collection.



                                                     The given Collection must not be null, and it must not contain any null elements.






                                                    share|improve this answer



























                                                      up vote
                                                      1
                                                      down vote













                                                      In Java 10:



                                                      List<T> newList = List.copyOf(oldList);


                                                      List.copyOf() returns an unmodifiable List containing the elements of the given Collection.



                                                       The given Collection must not be null, and it must not contain any null elements.






                                                      share|improve this answer

























                                                        up vote
                                                        1
                                                        down vote










                                                        up vote
                                                        1
                                                        down vote









                                                        In Java 10:



                                                        List<T> newList = List.copyOf(oldList);


                                                        List.copyOf() returns an unmodifiable List containing the elements of the given Collection.



                                                         The given Collection must not be null, and it must not contain any null elements.






                                                        share|improve this answer














                                                        In Java 10:



                                                        List<T> newList = List.copyOf(oldList);


                                                        List.copyOf() returns an unmodifiable List containing the elements of the given Collection.



                                                         The given Collection must not be null, and it must not contain any null elements.







                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Jun 26 at 15:51

























                                                        answered Apr 15 at 17:24









                                                        Oleksandr

                                                        7,72543467




                                                        7,72543467






















                                                            up vote
                                                            0
                                                            down vote













                                                            re: indexOutOfBoundsException, your sublist args are the problem; you need to end the sublist at size-1. Being zero-based, the last element of a list is always size-1, there is no element in the size position, hence the error.






                                                            share|improve this answer



























                                                              up vote
                                                              0
                                                              down vote













                                                              re: indexOutOfBoundsException, your sublist args are the problem; you need to end the sublist at size-1. Being zero-based, the last element of a list is always size-1, there is no element in the size position, hence the error.






                                                              share|improve this answer

























                                                                up vote
                                                                0
                                                                down vote










                                                                up vote
                                                                0
                                                                down vote









                                                                re: indexOutOfBoundsException, your sublist args are the problem; you need to end the sublist at size-1. Being zero-based, the last element of a list is always size-1, there is no element in the size position, hence the error.






                                                                share|improve this answer














                                                                re: indexOutOfBoundsException, your sublist args are the problem; you need to end the sublist at size-1. Being zero-based, the last element of a list is always size-1, there is no element in the size position, hence the error.







                                                                share|improve this answer














                                                                share|improve this answer



                                                                share|improve this answer








                                                                edited May 11 '15 at 17:12









                                                                Jorgesys

                                                                91k15234206




                                                                91k15234206










                                                                answered Oct 10 '13 at 17:51









                                                                Jon Nelson

                                                                14624




                                                                14624






















                                                                    up vote
                                                                    0
                                                                    down vote













                                                                    You can use addAll().



                                                                    eg : wsListCopy.addAll(wsList);






                                                                    share|improve this answer

























                                                                      up vote
                                                                      0
                                                                      down vote













                                                                      You can use addAll().



                                                                      eg : wsListCopy.addAll(wsList);






                                                                      share|improve this answer























                                                                        up vote
                                                                        0
                                                                        down vote










                                                                        up vote
                                                                        0
                                                                        down vote









                                                                        You can use addAll().



                                                                        eg : wsListCopy.addAll(wsList);






                                                                        share|improve this answer












                                                                        You can use addAll().



                                                                        eg : wsListCopy.addAll(wsList);







                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered Jan 3 at 4:30









                                                                        samaludheen cignes

                                                                        312




                                                                        312






















                                                                            up vote
                                                                            0
                                                                            down vote













                                                                            I can't see any correct answer. If you want a deep copy you have to iterate and copy object manually (you could use a copy constructor).






                                                                            share|improve this answer





















                                                                            • This is one of the few true Answers here. More details: stackoverflow.com/questions/715650/…
                                                                              – cellepo
                                                                              Aug 12 at 4:16















                                                                            up vote
                                                                            0
                                                                            down vote













                                                                            I can't see any correct answer. If you want a deep copy you have to iterate and copy object manually (you could use a copy constructor).






                                                                            share|improve this answer





















                                                                            • This is one of the few true Answers here. More details: stackoverflow.com/questions/715650/…
                                                                              – cellepo
                                                                              Aug 12 at 4:16













                                                                            up vote
                                                                            0
                                                                            down vote










                                                                            up vote
                                                                            0
                                                                            down vote









                                                                            I can't see any correct answer. If you want a deep copy you have to iterate and copy object manually (you could use a copy constructor).






                                                                            share|improve this answer












                                                                            I can't see any correct answer. If you want a deep copy you have to iterate and copy object manually (you could use a copy constructor).







                                                                            share|improve this answer












                                                                            share|improve this answer



                                                                            share|improve this answer










                                                                            answered Apr 27 at 11:47









                                                                            The incredible Jan

                                                                            185211




                                                                            185211












                                                                            • This is one of the few true Answers here. More details: stackoverflow.com/questions/715650/…
                                                                              – cellepo
                                                                              Aug 12 at 4:16


















                                                                            • This is one of the few true Answers here. More details: stackoverflow.com/questions/715650/…
                                                                              – cellepo
                                                                              Aug 12 at 4:16
















                                                                            This is one of the few true Answers here. More details: stackoverflow.com/questions/715650/…
                                                                            – cellepo
                                                                            Aug 12 at 4:16




                                                                            This is one of the few true Answers here. More details: stackoverflow.com/questions/715650/…
                                                                            – cellepo
                                                                            Aug 12 at 4:16










                                                                            up vote
                                                                            0
                                                                            down vote













                                                                            If you do not want changes in one list to effect another list try this.It worked for me
                                                                            Hope this helps.



                                                                              public class MainClass {
                                                                            public static void main(String a) {

                                                                            List list = new ArrayList();
                                                                            list.add("A");

                                                                            List list2 = ((List) ((ArrayList) list).clone());

                                                                            System.out.println(list);
                                                                            System.out.println(list2);

                                                                            list.clear();

                                                                            System.out.println(list);
                                                                            System.out.println(list2);
                                                                            }
                                                                            }

                                                                            > Output:
                                                                            [A]
                                                                            [A]

                                                                            [A]





                                                                            share|improve this answer

























                                                                              up vote
                                                                              0
                                                                              down vote













                                                                              If you do not want changes in one list to effect another list try this.It worked for me
                                                                              Hope this helps.



                                                                                public class MainClass {
                                                                              public static void main(String a) {

                                                                              List list = new ArrayList();
                                                                              list.add("A");

                                                                              List list2 = ((List) ((ArrayList) list).clone());

                                                                              System.out.println(list);
                                                                              System.out.println(list2);

                                                                              list.clear();

                                                                              System.out.println(list);
                                                                              System.out.println(list2);
                                                                              }
                                                                              }

                                                                              > Output:
                                                                              [A]
                                                                              [A]

                                                                              [A]





                                                                              share|improve this answer























                                                                                up vote
                                                                                0
                                                                                down vote










                                                                                up vote
                                                                                0
                                                                                down vote









                                                                                If you do not want changes in one list to effect another list try this.It worked for me
                                                                                Hope this helps.



                                                                                  public class MainClass {
                                                                                public static void main(String a) {

                                                                                List list = new ArrayList();
                                                                                list.add("A");

                                                                                List list2 = ((List) ((ArrayList) list).clone());

                                                                                System.out.println(list);
                                                                                System.out.println(list2);

                                                                                list.clear();

                                                                                System.out.println(list);
                                                                                System.out.println(list2);
                                                                                }
                                                                                }

                                                                                > Output:
                                                                                [A]
                                                                                [A]

                                                                                [A]





                                                                                share|improve this answer












                                                                                If you do not want changes in one list to effect another list try this.It worked for me
                                                                                Hope this helps.



                                                                                  public class MainClass {
                                                                                public static void main(String a) {

                                                                                List list = new ArrayList();
                                                                                list.add("A");

                                                                                List list2 = ((List) ((ArrayList) list).clone());

                                                                                System.out.println(list);
                                                                                System.out.println(list2);

                                                                                list.clear();

                                                                                System.out.println(list);
                                                                                System.out.println(list2);
                                                                                }
                                                                                }

                                                                                > Output:
                                                                                [A]
                                                                                [A]

                                                                                [A]






                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Aug 7 at 6:51









                                                                                Aashis Shrestha

                                                                                65




                                                                                65






















                                                                                    up vote
                                                                                    -2
                                                                                    down vote













                                                                                    subList function is a trick, the returned object is still in the original list.
                                                                                    so if you do any operation in subList, it will cause the concurrent exception in your code, no matter it is single thread or multi thread.






                                                                                    share|improve this answer

























                                                                                      up vote
                                                                                      -2
                                                                                      down vote













                                                                                      subList function is a trick, the returned object is still in the original list.
                                                                                      so if you do any operation in subList, it will cause the concurrent exception in your code, no matter it is single thread or multi thread.






                                                                                      share|improve this answer























                                                                                        up vote
                                                                                        -2
                                                                                        down vote










                                                                                        up vote
                                                                                        -2
                                                                                        down vote









                                                                                        subList function is a trick, the returned object is still in the original list.
                                                                                        so if you do any operation in subList, it will cause the concurrent exception in your code, no matter it is single thread or multi thread.






                                                                                        share|improve this answer












                                                                                        subList function is a trick, the returned object is still in the original list.
                                                                                        so if you do any operation in subList, it will cause the concurrent exception in your code, no matter it is single thread or multi thread.







                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered Jun 4 '15 at 14:20









                                                                                        weixingsun

                                                                                        9




                                                                                        9






























                                                                                             

                                                                                            draft saved


                                                                                            draft discarded



















































                                                                                             


                                                                                            draft saved


                                                                                            draft discarded














                                                                                            StackExchange.ready(
                                                                                            function () {
                                                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14319732%2fhow-to-copy-a-java-util-list-into-another-java-util-list%23new-answer', 'question_page');
                                                                                            }
                                                                                            );

                                                                                            Post as a guest















                                                                                            Required, but never shown





















































                                                                                            Required, but never shown














                                                                                            Required, but never shown












                                                                                            Required, but never shown







                                                                                            Required, but never shown

































                                                                                            Required, but never shown














                                                                                            Required, but never shown












                                                                                            Required, but never shown







                                                                                            Required, but never shown







                                                                                            Popular posts from this blog

                                                                                            404 Error Contact Form 7 ajax form submitting

                                                                                            How to know if a Active Directory user can login interactively

                                                                                            TypeError: fit_transform() missing 1 required positional argument: 'X'