Given 3 variables (homeNumber,mobileNumber and workNumber), which can be null, but atleast one of those will be a String, I need to return a String array so I can use it later on an Android Dialog. I'm having troubles doing this. I tried doing it in an ArrayList and removing all null elements, which leaves an ArrayList with only Strings, like I want, but when trying to change it to an Array I get a ClassCast exception on the last line.
ArrayList numberList = new ArrayList();
numberList.add(homeNumber);
numberList.add(mobileNumber);
numberList.add(workNumber);
numberList.removeAll(Collections.singleton(null));
final String[] items= (String[]) numberList.toArray();
Any ideas how to fix this?
-
2You should check if the data you add in your arraylist are null before inserting them. Why do you want to transform your ArrayList in String Array? Why you don't build an ArrayList<String>?Jeremy D– Jeremy D2011年12月27日 21:15:20 +00:00Commented Dec 27, 2011 at 21:15
-
You cannot cast non generic ArrayList to an array of a given object, since it can contain objects of different classes. Given the fact that this is Android code why not use generics as Jeremy stated above?Wojciech Owczarczyk– Wojciech Owczarczyk2011年12月27日 21:20:18 +00:00Commented Dec 27, 2011 at 21:20
5 Answers 5
String[] items = new String[numberList.size()];
numberList.toArray(items);
1 Comment
You can do one of two things:
Pass in the type of array you want to get (there's no need to instantiate a full length array, performance is the same regardless):
final String[] items= (String[]) numberList.toArray(new String[0]);
However, the better solution is to use generics:
List<String> numberList = new ArrayList<String>(); final String[] items= (String[]) numberList.toArray();
Comments
The return type of ArrayList.toArray() is Object[], unless you pass an array as the first argument. In that case the return type has the same type as the passed array, and if the array is large enough it is used. Do this:
final String[] items= (String[])numberList.toArray(new String[3])
1 Comment
Use the other method toArray() of List class:
numberList.toArray(new String[numberList.size()]);
2 Comments
String[] itemsChange
ArrayList numberList = new ArrayList();
to
List<String> numberList = new ArrayList<String>();