Marcel Marino Marcel Marino - 3 months ago 14
Java Question

Get String from ArrayList inside an ArrayList inside an ArrayList

I need to get three levels down into an array list. Here is my code on how I create the final product "rowList":

ArrayList<ArrayList> rowList = new ArrayList<ArrayList>();
ArrayList<ArrayList<String>> appList =new ArrayList<ArrayList<String>>();
ArrayList<String> arr = new ArrayList<String>();

int Id = -1;
int cc = rsmd.getColumnCount();
while(rs.next()){
if(Id == -1){
arr.add(rs.getString("name"));
Id= Integer.parseInt(rs.getString("Id"));
}
if(Id!= Integer.parseInt(rs.getString("Id"))){
Id= Integer.parseInt(rs.getString("Id"));
rowList.add(appList);
appList = new ArrayList<ArrayList<String>>();
arr.add(rs.getString("name"));

}

for(int i=2; i < rsmd.getColumnCount();i++){
arr.add(rs.getString(rsmd.getColumnName(i)));
}
appList.add(arr);
arr = new ArrayList<>();
}
rowList.add(appList);


So in the end rowlist will look something like this:

[0]
[0]
[0]Property 1
[1]Property 2
[2]Property 3
[1]
[0]Property 1
[1]Property 2
[2]Property 3
[1]
[0]
[0]Property 1
[1]Property 2
[2]Property 3
[1]
[0]Property 1
[1]Property 2
[2]Property 3


So my question would be how to get to the properties, the last level in the nested array? I can use rowList.get(0).get(0).toString() to return the string array, but rowList.get(0).get(0).get(0) doesn't work, and instead gives the error: cannot find symbol.

I would also like to be able to remove a property after I've retrieved it and set it to a string. That part can easily be worked around though, so it isn't vital.

Answer

This is because you're using a raw type:

ArrayList<ArrayList> rowList = new ArrayList<ArrayList>();

rowList.get(0) returns an ArrayList. Antoher .get(0) will return an Object, because you're using a raw type. And Object does not have a get method.

But Object does have a toString method, so you can call toString.


You simply have to change the declaration. This can be made easier using the diamond:

ArrayList<ArrayList<ArrayList<String>>> rowList = new ArrayList<>();
ArrayList<ArrayList<String>> appList = new ArrayList<>();
ArrayList<String> arr = new ArrayList<>();