Dante
Dante

Reputation: 457

How to get an element from an ArrayList<ArrayList<String[]>?

I have an arraylist of arraylists having string[]s i.e.,

ArrayList<ArrayList> arraymain = new ArrayList<>();
ArrayList<String[]> arraysub = new ArrayList<>();

Now, adding the elements to arraysub,

arraysub.add(new String[]{"vary","unite"});
arraysub.add(new String[]{"new","old"});

I tried:

arraymain.get(0).get(0)[1];

But I'm getting an error : Array type expected; found 'java.lang.Object' How can I now retrieve the data(the string stored in the string[])?

Upvotes: 0

Views: 126

Answers (3)

Saroj Singh
Saroj Singh

Reputation: 1

    ArrayList<ArrayList<String>> outer = new ArrayList<ArrayList<String>>();
    ArrayList<String> inner = new ArrayList();

    inner.add("ABC");
    inner.add("XYZ");
    inner.add("CDF");

    outer.add(inner);

    ArrayList<String> orderList = outer.get(0);
    String first = orderList.get(0);
    String second = orderList.get(1);
    String third = orderList.get(2);

    System.out.println("FirstValue: "+first);
    System.out.println("SecondValue: "+second);
    System.out.println("ThirdValue: "+third);

Upvotes: 0

karun
karun

Reputation: 91

But arraymain accepts arraylists of type string array only, If u want to store different arraylists of different array types in arraymain then this will be the solution:

ArrayList<ArrayList<Object[]>> arraymain = new ArrayList<ArrayList<Object[]>>();
ArrayList<Object[]> arraysub = new ArrayList<Object[]>();
arraysub.add(new String[]{"kk"});
arraymain.add(arraysub);
ArrayList<Object[]> arraysub2 = new ArrayList<Object[]>();
arraysub2.add(new Integer[]{1,2});
arraymain.add(arraysub2);

Upvotes: 2

Eran
Eran

Reputation: 393846

Change the type of the inner ArrayList:

ArrayList<ArrayList<String[]>> arraymain = new ArrayList<>();
ArrayList<String[]> arraysub = new ArrayList<>();

This way arraymain.get(0).get(0) will return a String[] instead of an Object.

It would be even better if you declare the variables as Lists, instead of forcing a specific List implementation:

List<List<String[]>> arraymain = new ArrayList<>();
List<String[]> arraysub = new ArrayList<>();

Upvotes: 6

Related Questions