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"
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.)
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.
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.
You don't need to reinvent the wheel, here's the toArray()
method:
String []dsf = new String[al.size()]; al.toArray(dsf);
List<String> list=new ArrayList<String>(); list.add("sravan"); list.add("vasu"); list.add("raki"); String names[]=list.toArray(new String[list.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