Reputation: 3948
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.
Upvotes: 0
Views: 3437
Reputation: 2125
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
Upvotes: 2
Reputation: 7899
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()][]);
Upvotes: 0
Reputation: 10427
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();
}
Upvotes: 1