2

I want to add the an index of a 2 dimensional ArrayList to the same ArrayList. Code should be something like the following but index numbers and the same ArrayList must be involved:

ArrayList<String> a[0] = new ArrayList<>(Arrays.asList("A", "B", "C"));
ArrayList<String> a[1] = a[0];

Of course this code won't work. Thank you in advance...

2
  • 1
    Post an example of your desired output. Commented Dec 27, 2015 at 9:26
  • a(0) = A, B, C --- a(1) = A, B, C must be done through index numbers or similar Commented Dec 27, 2015 at 9:44

1 Answer 1

3

a[i] is used to access and assign array elements.

Assuming a is declared as :

ArrayList<ArrayList<String>> a = new ArrayList<>();

You assign the inner lists with :

a.set(0,new ArrayList<String>(Arrays.asList("A", "B", "C"));
a.set(1,a.get(0));

Note that this code will work only if a's size is at least 2 (i.e. it already has values for indices 0 and 1). If a is empty, you should use :

a.add (new ArrayList<String>(Arrays.asList("A", "B", "C"));
a.add (a.get(0));
Sign up to request clarification or add additional context in comments.

21 Comments

ArrayList is backed by an array and when you instantiate with new ArrayList<>(), it creates an array of size 0 and when you do set with index it would give you IOOBE.
@SMA That's true. That's why I gave two options. The first option only works if the ArrayList already contains elements at the 0 and 1 indices.
@Otag a.get(1).get(2)
During my debugging efforts debugger gives a.add(a.get(donsay - 1)); the following exception => java.lang.RuntimeException: Unable to start activity ComponentInfo{chessactivesekizsatirvetekliarray.com.sekizsatirvetekliarray/chessactivesekizsatirvetekliarray.com.sekizsatirvetekliarray.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1 <-------->donsay is the integer variable for looping purposes...Any ideas on what is going on??
@Otag this means that a contains just one element, whose index is 0, but you are trying to access an element at index 1.
|

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.