1

I have an array of object like A[] a;

I also have a list of A like List<A> b = new ArrayList<A>();

I am wondering how to add a to b?

1
  • 1
    Do you want to add the contents of a to b, or do you want to add the array itself to b? Commented Sep 22, 2011 at 12:45

6 Answers 6

7

Just use the addAll() method with Arrays.asList() as argument:

b.addAll(Arrays.asList(a));
Sign up to request clarification or add additional context in comments.

2 Comments

Looks like you came up with the exact same answer as mine, but you posted 2 minutes later ;-) Sadly, you got more ups out of it :p
This solution is more expensive and more complex than ABCD's solution.
6

Try:

b.addAll(Arrays.asList(a));

Comments

3

Iterate the array and add each element

for( A element : a ) { 
    b.add( element ) 
}

2 Comments

+1 Sometimes keeping it simple is best. Nothing difficult here
I would advice against writing a custom loop, but for reusing an existing and easily understable generic building block (method).
3

Assuming you are adding the contents of a to b, you would want to use Collections.addAll(b, a);

1 Comment

This solution is better than most other here, since it removes one conversion step (array -> list)
2

list.addAll(Arrays.asList());

For example :

b.addAll(Arrays.asList("Larry", "Moe", "Curly"));

1 Comment

This will convert a from an array to a list but not add it to b.
0
 List<A> b = new ArrayList<A>();
 b.addAll(Arrays.asList(a));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.