leonsas
leonsas

Reputation: 4898

ArrayList to a String Array

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?

Upvotes: 0

Views: 237

Answers (5)

Chris Cashwell
Chris Cashwell

Reputation: 22859

Change

ArrayList numberList = new ArrayList();

to

List<String> numberList = new ArrayList<String>();

Upvotes: 0

oneself
oneself

Reputation: 40231

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();

Upvotes: 1

True Soft
True Soft

Reputation: 8786

Use the other method toArray() of List class:

numberList.toArray(new String[numberList.size()]);

Upvotes: 0

Ashterothi
Ashterothi

Reputation: 3282

String[] items = new String[numberList.size()];
numberList.toArray(items);

Upvotes: 8

Spike Gronim
Spike Gronim

Reputation: 6182

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

Upvotes: 0

Related Questions