-1

Why am I getting Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException ERRO while executing the following code?

int[] things={11,22,33,44};
List<int[]>Listdata = Arrays.asList(things);
int[] n=Listdata.get(1);
System.out.println(n[1]);

It works fine if i put get(0)

LondonRob
  • 73,083
  • 37
  • 144
  • 201
Debojit Paul
  • 213
  • 4
  • 12
  • 2
    You only put one array in your List, so why would you expect to have one at the second index? – Alexis C. Dec 10 '14 at 22:30
  • @SolomonPByer: You most certainly can have a `List`. It's binding the generic type `T` to an `int[]` instead. – Makoto Dec 10 '14 at 22:32
  • @DebojitPaul What do you think `List` is ? If you can answer this question, you can answer why your code doesn't work. – Alexis C. Dec 10 '14 at 22:33
  • Then how to access specific data from a list at a time.What are the other methods. – Debojit Paul Dec 10 '14 at 22:34
  • Clarification on @ZouZou's first comment: Array and (standard) list indexing starts at `0`, not `1`. You have **1** object (of type `int[]`) in your list. Its index is `0`. Index `1` is out of bounds of the data structure. – Zéychin Dec 10 '14 at 22:54

1 Answers1

2

An int[] array maps most naturally to a List<Integer>. Unfortunately, there is no built-in way to convert directly from an int array to an Integer list, due to the boxing that is required. You'll have to build the List manually.

int[] things = {11, 22, 33, 44};

List<Integer> list = new ArrayList<>();
for (int i: things) {
    list.add(i);
}

int n = list.get(1);
System.out.println(n);

The excellent Guava library from Google has a convenience method you could use, if you're willing to rely on a third-party library call.

int[] things = {11, 22, 33, 44};
List<Integer> list = Ints.asList(things);
int n = list.get(1);
System.out.println(n);

Or if your goal is simply to get a List of numbers, you could skip the intermediate array.

List<Integer> list = Arrays.asList(11, 22, 33, 44);
Community
  • 1
  • 1
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    `List list = IntStream.of(things).boxed().collect(Collectors.toList());` would also do the trick with Java 8! – Alexis C. Dec 10 '14 at 22:45
  • Or if you don't mind autoboxing, `Integer[] things = {11, 22, 33, 44};` then `List list = Arrays.asList(things);`. – gknicker Dec 11 '14 at 01:33