2

I am using an ArrayList of to create lists. For example:

Index 0: 1 3
Index 1: 4 5
Index 2: 1 3 7

How can I access the second element of the first index of the ArrayList? Couldn't find the answer on Google, so I asked here.

8
  • 1
    Why not just use a 2d array? Commented Jan 8, 2015 at 16:21
  • 1
    I googled "ArrayList of integers" and the first result was stackoverflow.com/questions/14421943/… Commented Jan 8, 2015 at 16:22
  • 1
    Show us some code, because a ArrayList isn't an array of Integer(s). Commented Jan 8, 2015 at 16:23
  • 2
    I found the correct answer on @Fev, I don't use a 2d Array because it's harder to add elements dinamically. ArrayList of integer[] it's much easier. Commented Jan 8, 2015 at 16:27
  • 1
    @HanletEscaño That looks like an accident. This is about an "ArrayList of arrays of integers", not "ArrayList of integers". But the second phrase happened to work because someone put the wrong title on their question. My point is: don't assume that everyone should just be able to find things with Google. It's not always easy to guess what search terms to put in. Commented Jan 8, 2015 at 16:32

3 Answers 3

4
yourList.get(0)[1]; // that's it !!

If you want to iterate over it :

for (Integer[] outer : yourList) {
  for(Integer inner : outer) {
    System.out.println(inner);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

If it was so simple why I couldn't find it over the internet, thanks a lot.Gonna try it ! Mark answer after time pass.
2

By your question, I am guessing you have something like this?

List<Integer[]> list = new ArrayList<Integer[]>();
Integer[] a1 = {1,3};
Integer[] a2 = {4,5};
Integer[] a3 = {1,3,7};

list.add(a1);
list.add(a2);
list.add(a3);

Then all you need to do is simply call:

Integer result = list.get(0)[1];

The get(0) pulls the first Integer[] out of the list, then to get the second element, you use [1]

Comments

0

where do you see the exception? have you tried this?

    List<Integer[]> list = new ArrayList<Integer[]>(3);
    Integer[] a1 = {1,3};
    Integer[] a2 = {4,5};
    Integer[] a3 = {1,3,7};

    list.add(a1);
    list.add(a2);
    list.add(a3);

    Integer result = list.get(0)[1];

There aren't any exception. The arraylist have three elementes because you have three elemente (a1,a2,a3),

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.