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 :-)
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.
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.
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.)
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.
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()]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With