cofactor
asked on
String array to Arralist and vice versa conversion
How do I convert
String[] to ArrayList
and
ArrayList to String[]
Reason :
I have a VO field String[] . I need to poulate this field in a while loop . So, I need to know the above two conversions.
String[] to ArrayList
and
ArrayList to String[]
Reason :
I have a VO field String[] . I need to poulate this field in a while loop . So, I need to know the above two conversions.
ASKER
Not clear.
The code using strings:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package convertarray;
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* @author darren
*/
public class Convert {
private ArrayList<String> al;
private ArrayList<String> al2;
private String ia[];
public void createArrList() {
al = new ArrayList<String>();
al.add("a");
al.add("b");
al.add("c");
al.add("d");
System.out.println("Contents of al: " + al);
ia = new String[al.size()];
ia = al.toArray(ia);
String sum = "";
for (String i : ia) {
sum += i + ",";
}
System.out.println("Strings are: " + sum);
//convert array to Arraylist
al2 = new ArrayList<String>();
al2.addAll(Arrays.asList(ia));
System.out.println("From arrayaylist:");
for (String st : al2) {
System.out.println(st);
}
}
}
I've taken the given example, converted it to use Strings, it takes a creates a string arraylist converts it to a string array then converts the array to a arraylist.
Darren
Darren
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Excellent
I believe that Arrays.asList(Array) circumnavigates using the list method above (line 43 in my example)? No to happy about the point allocation here sorry?
darren is right. Actually it's even simpler (as long as mutation doesn't occur). Happy to split points btw
List<String> converted = Arrays.asList(ia);
and for the reverse, all you need to do is create a List of the same size and each array element to it.