23

Who knows the easiest way to convert a List of strings to an ArrayList?

I tried setting (ArrayList) before the code but this doesn't do anything.

0

2 Answers 2

90

Sure:

ArrayList arrayList = new ArrayList(list);

That works because List<T> implements ICollection.

However, I'd strongly advise you to avoid ArrayList (and other non-generic collections) if at all possible. Can you refactor whatever code wants an ArrayList to use a generic collection instead?

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

10 Comments

I have a similar use case...can you please explain why you recommend avoid ArrayList and other non-generic collections?
@AJW: Because they aren't safe at compile-time - they don't stop you from putting the "wrong" kind of thing in (compared with what you expect) and you need to cast everything coming out of them.
I understand. Almost every tutorial and codelabs that I've reviewed dealing with a RecyclerView list and its adapter show the use of an ArrayList. Yet the Room database DAOs seem to use List exclusively to return data from for example a SQLite database. So your recommendation would be to use a List in the RecyclerView and its adapter, since the DAO is returning a List?
@AJW: I've never even heard of RecyclerView before that comment (that I remember, anyway) I'm afraid.
@AJW: If this is Android, bear in mind that there's a big difference between ArrayList in Java (which is generic) and ArrayList in .NET (which isn't).
|
10

ArrayList has a constructor which accepts an ICollection. Since List<T> implements ICollection, the following should work:

var myArrayList = new ArrayList(myList);

Comments

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.