Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :-)

like image 717
stefan.at.wpf Avatar asked May 07 '11 15:05

stefan.at.wpf


People also ask

Is String [] same as list String?

String [] will always be fixed size, but it's faster than Lists. If your stored variables are always the same count, and you consider performance, use String[]. If you don't expect huge amounts of Strings, better is to use Lists. Lists are resizable, and are part of Collections.

Can ArrayList be converted to String?

If you happen to be doing this on Android, there is a nice utility for this called TextUtils which has a . join(String delimiter, Iterable) method. List<String> list = new ArrayList<String>(); list. add("Item 1"); list.

How do you cast an ArrayList to an array?

To convert ArrayList to array in Java, we can use the toArray(T[] a) method of the ArrayList class. It will return an array containing all of the elements in this list in the proper order (from first to last element.)

How do you join an ArrayList to a String in Java?

To convert the contents of an ArrayList to a String, create a StringBuffer object append the contents of the ArrayList to it, finally convert the StringBuffer object to String using the toString() method.


2 Answers

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()]);
like image 136
Peter Lawrey Avatar answered Sep 18 '22 07:09

Peter Lawrey


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()]);
like image 42
Kaj Avatar answered Sep 19 '22 07:09

Kaj