简体   繁体   中英

Java ArrayList of Integer[], how to access elements

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.

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

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]

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

You have List<Integer[]> l = new ArrayList<Integer[]>(3);

if you want the second element of the first index:

l.get(0)[1].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM