Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting ArrayList to Array in java

I have an ArrayList with values like "abcd#xyz" and "mnop#qrs". I want to convert it into an Array and then split it with # as delimiter and have abcd,mnop in an array and xyz,qrs in another array. I tried the following code:

String dsf[] = new String[al.size()];               for(int i =0;i<al.size();i++){   dsf[i] = al.get(i); } 

But it failed saying "Ljava.lang.String;@57ba57ba"

like image 805
Shruthi Avatar asked Mar 29 '12 16:03

Shruthi


People also ask

Can you convert an ArrayList to an array in Java?

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 convert a list to an array in Java?

The best and easiest way to convert a List into an Array in Java is to use the . toArray() method. Likewise, we can convert back a List to Array using the Arrays. asList() method.

How would you convert a list to an array?

Create a List object. Add elements to it. Create an empty array with size of the created ArrayList. Convert the list to an array using the toArray() method, bypassing the above-created array as an argument to it.


2 Answers

You don't need to reinvent the wheel, here's the toArray() method:

String []dsf = new String[al.size()]; al.toArray(dsf); 
like image 156
talnicolas Avatar answered Sep 28 '22 06:09

talnicolas


List<String> list=new ArrayList<String>(); list.add("sravan"); list.add("vasu"); list.add("raki"); String names[]=list.toArray(new String[list.size()]) 
like image 37
Sravan Kumar Limbadri Avatar answered Sep 28 '22 08:09

Sravan Kumar Limbadri