Casting ArrayList <String> to String []

1) I wonder why I can not do this:

ArrayList<String> entries = new ArrayList<String>();
entries.add("entry");
String[] myentries = (String[])entries.toArray();

What is wrong with that? (You can ignore the second line of code, this does not apply to the question)

2) I know that my goal can be achieved 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 preferred way to convert an ArrayList to a String Array? Is there a better / shorter way?

Many thanks: -)

+5
source share
4 answers

The first example returns Object[]because the list does not know what type of array you need and cannot be attributed toString[]

You can make the second one a little shorter

String[] myentries = entries.toArray(new String[entries.size()]);
+13
source

, ArrayList, String, Object .

2. , , :

String[] myentries = entries.toArray(new String[entries.size()]);
+3
List<String> list = ...;
String[] array = list.toArray(new String[list.size()]);
+2

( Generics Java). , toArray, , , List . , [] . , toArray. , .. . , .

0

All Articles