0

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[])?

3 Answers 3

6

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<>();
Sign up to request clarification or add additional context in comments.

1 Comment

Oh! I see. I need to declare the Type of sub arraylist as well in the main array itself. That was quite simple. Thank you :)
2

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);

1 Comment

Thank you. Though not now, this is useful to know. I’ll keep this in mind. +1 for that.
0
    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);

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.