0

I have a

List<ArrayList> arg = new ArrayList<ArrayList>();

with

[[logo], [cd_branche], [lib_branche]],

(other arguments not relevant) 

[[1111,22222,3333]],[[2222,324,432]]...

and I want to cast it to a String[] so I did this

    Object[] obj = arg.toArray();
    String[] headers =new String[obj.length];

    for(int i=0;i<headers.length;i++) { 
        headers[i]= (String) obj[i]; 
        }

but I'm getting

java.util.ArrayList cannot be cast to java.lang.String

The output I'm looking for is

headers[0]=logo
headers[1]=cd_branche
headers[2]=lib_branche

Using Java 6

2 Answers 2

1

It sounds like you want it to be an array of strings (i.e. "[["logo", "cd_branche", "lib_cranche"],[..],[..],[1111,22222,3333],[2222,324,432]").

In that case simply do:

Object[] obj = arg.toArray();
String[] headers =new String[obj.length];
for(int i=0;i<headers.length;i++) { 
    headers[i]= Arrays.toString(obj);
}

And each one of your ArrayList objects inside obj will be returned in string array format.


UPDATE: Since you want it as a flat array, you'll need to (a) compute the size of the array needed and (b) run through your object with two loops and make a deep search as such:

int size = 0;
for (int i = 0; i < arg.size(); size += arg.get(i++).size());

String[] headers =new String[size];
for(int count = 0, i=0;i<arg.size();i++) {
    for (int j=0; j< arg.get(i).size(); j++) {
        headers[count++]= arg.get(i).get(j).toString();
    }
}               
Sign up to request clarification or add additional context in comments.

1 Comment

No, what I want is a String[] headers with headers[1]="logo" headers[2]="cd_branch" and so on
0

String headers = "";
for (String header:arg) {headers += header;}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.