1

Is it possible to convert:

ArrayList<?> objects; to ArrayList<String>() if you know objects only contains Strings?

2 Answers 2

7

Yes; just cast it.
You will get a compile-time warning, because even though you know that, the compiler doesn't.

Beware that if someone else adds some other class to the list after you cast it, you will get exceptions when you try to use it.

This is only true because of type erasure.

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

Comments

2
ArrayList<?> anonymList = null;
ArrayList<String> strings = (ArrayList<String>) anonymList;

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.