Link to home
Start Free TrialLog in
Avatar of cofactor
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.

 
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

See ArrayList.toArray

and for the reverse, all you need to do is create a List of the same size and each array element to it.

Avatar of cofactor
cofactor

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

Open in new window

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
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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);

Open in new window