Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ArrayList<String> to String[] array [duplicate]

I'm working in the android environment and have tried the following code, but it doesn't seem to be working.

String [] stockArr = (String[]) stock_list.toArray(); 

If I define as follows:

String [] stockArr = {"hello", "world"}; 

it works. Is there something that I'm missing?

like image 264
locoboy Avatar asked Mar 21 '11 05:03

locoboy


People also ask

How do you return an ArrayList as a String?

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.

Does ArrayList have a toString?

Note: The ArrayList class does not have its own toString() method. Rather it overrides the method from the Object class.


2 Answers

Try this

String[] arr = list.toArray(new String[list.size()]); 
like image 45
st0le Avatar answered Oct 15 '22 00:10

st0le


Use like this.

List<String> stockList = new ArrayList<String>(); stockList.add("stock1"); stockList.add("stock2");  String[] stockArr = new String[stockList.size()]; stockArr = stockList.toArray(stockArr);  for(String s : stockArr)     System.out.println(s); 
like image 54
Prince John Wesley Avatar answered Oct 15 '22 00:10

Prince John Wesley