-1

You will have to forgive me for asking this but I can't seem to find the exact answer to my question. I need to know how to copy this list:

List<String> jpmcRouting

into a new List (the name doesn't matter).

I have found answers on copying an ArrayList but not a standard list. I've tried a lot of solutions but nothing seems to work. I would appreciate any help!

4
  • 2
    You know that a 'standard' List is an interface right? That it cannot be instantiated Commented Mar 24, 2016 at 18:23
  • What kind of List are you trying to copy? Do you want the result to have the same class as the original? Commented Mar 24, 2016 at 18:25
  • Possible duplicate of How to copy a java.util.List into another java.util.List Commented Mar 24, 2016 at 18:26
  • RAnders00 this is not a duplicate. I saw that answer and did not understand it.. The list has <SomeBean> which makes no sense to me what kind of list that is and I tired the method of replacing <SomeBean> with <String> and it did not work. Commented Mar 24, 2016 at 18:28

4 Answers 4

2
List<String> myCopy = new ArrayList<String>(jpmcRouting);

does the job. Collections.copy is not what you want; that only works if the destination list already has the right number of elements.

Sign up to request clarification or add additional context in comments.

Comments

0

I could be wrong, but I think Collections.copy(b, a); will do the trick.

Comments

0

Do this:

List<String> b = new ArrayList<String>(jpmcRouting.size());
Collections.copy(b, jpmcRouting);

3 Comments

Thanks that's what I was looking for, I'll accept in 5 minutes.
This will throw an IndexOutOfBoundsException at runtime unless the original list is empty, meaning it will basically never work.
Yes Louis is correct, I got an error. Any suggestion on how to fix this?
0

The simplest way for me is:

List<String> copy = jpmcRouting.stream().collect(Collectors.toList());

if your result doesnt depend on order of elements in list, you can use

List<String> copy = jpmcRouting.parallelStream().collect(Collectors.toList());

it will work mutch faster, but it can change order of elements

3 Comments

Using a parallel stream means that it may be done using parallelism. It won't change the order of the elements in the answer.
I got an index out of bounds for this.
are you sure? this is really safe... All methods are internal java methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.