Casting ArrayList<String> to String[]
1) I am wondering why I can't do this:
ArrayList<String> entries = new ArrayList<String>();
entries.add("entry");
String[] myentries = (String[])entries.toArray();
What's wrong with that? (You might ignore the second code line, it's not relevant for the question)
2) I know my goal can be reached using this code:
ArrayList<String> entries = new ArrayList<String>();
entries.add("entry");
String开发者_如何转开发[] myentries = new String[entries.size()];
myentries = entries.toArray(myentries)
Is this the prefered way of converting the ArrayList to a String Array? Is there a better / shorter way?
Thank you very much :-)
The first example returns an Object[]
as the list doesn't know what type of array you want and this cannot be cast to a String[]
You can make the second one slightly shorter with
String[] myentries = entries.toArray(new String[entries.size()]);
The backing array created by the ArrayList isn't a String array, it's an Object array, and that's why you can't cast it.
Regarding case 2. That's the common way to convert it to an array, but you can make it a bit less verbose by writing:
String[] myentries = entries.toArray(new String[entries.size()]);
List<String> list = ...;
String[] array = list.toArray(new String[list.size()]);
The type of entries is lost (as Generics are erased in Java). So when you do the toArray call it can only return the Object type back, as it knows the List must contain Objects. So you can get back an Object[] with your Strings in it. If you want to have an array of Strings then you need to pass that into the toArray method. With casting you can't narrow the Array reference i.e. you can't cast an array of Objects into an array of Strings. But you could go the opposite way, as they are covariant.
精彩评论