简体   繁体   中英

Extract String[] elements from a list

at my work I've got the following source code:

import java.util.ArrayList;
import java.util.List;

public class Temporaer
{
    public static void main(String[] args)
    {
        List stringArrayList = new java.util.ArrayList();
        stringArrayList.add(fillStringArrayElement("a", "b"));
        stringArrayList.add(fillStringArrayElement("c", "d"));

        String[] listElement;

        /*
         * I'm stuck here, because I don't know what I have to do
         */

        System.out.println(listElement.length);
    }

    //Just a method to fill a list easily
    private static String[] fillStringArrayElement (String firstElem, String secondElem)
    {
        String[] stringArrayListElement = new String[2];
        stringArrayListElement[0] = firstElem;
        stringArrayListElement[1] = secondElem;
        return stringArrayListElement;
    }
}

My goal is it to extract each list item and work with those.

I tried to use the toArray[T[]) method as mentioned here . Though it generates an java.lang.ArrayStoreException . Note: I cannot change the type of the list because the list is filled by an extern service. Maybe I have to convert the list first...

Can someone show me a way to achive my goal? Thanks in advanced.

Iterator is an interface in java used to iterate over a Collection like ArrayList or other Collection framework classes. Before reading ArrayList make sure values are available using the size() method.

Here a sample working snippet for your problem.

    String [] myArray ;
    if (stringArrayList.size()>0){
        Iterator<String [] > i = stringArrayList.iterator();
        while(i.hasNext()){
                  myArray =  i.next();
                  for(String s : myArray)
                      System.out.println(s);
                }
                }

        }     

Don't use Raw ArrayList , instead use Generics

Use this:

    List<String[]> stringArrayList = new java.util.ArrayList<String[]>();
    stringArrayList.add(new String[]{"a", "b"});
    stringArrayList.add(new String[]{"c", "d"});

    //if you cant to convert the stringArrayList to an array:
    String[][] listElement = stringArrayList.toArray(new String[0][]);
    for (String[] inArr : listElement){
        for (String e : inArr){
            System.out.print(e + " ");
        }
        System.out.println();
    }
String[] listElement;

Above statements is incorrect because you are keeping arrays in list so your listElement must contain String[] .

String [][] listElement

Something like below.

listElement=stringArrayList.toArray(new String[stringArrayList.size()][]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM