This code throw
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
on last line. Is it bug or what? (JDK 7)
int ar[] = {1,2,3};
List arList = Arrays.asList(ar);
arList.set(1,8);
This code throw
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
on last line. Is it bug or what? (JDK 7)
int ar[] = {1,2,3};
List arList = Arrays.asList(ar);
arList.set(1,8);
No, Arrays.asList
expects Integer []
, but you are passing int[]
. This should fix it.
Integer ar[] = {1,2,3};
This is what my inspection says about using a primitive array where a var-arg type is expected.
Reports any calls to a variable-argument method which has a primitive array in in the variable-argument position (e.g
System.out.printf("%s", new int[]{1, 2, 3})
). Such a primitive-array argument may be confusing, as it will wrapped as a single-element array, rather than each individual element being boxed, as might be expected.
This means that what you have is a List with only one element in it. And this element is your int[]
.
And you can't access position 1
in this list since there's only one element. Thus arList.set(1,8);
will throw ArrayIndexOutOfBoundsException
.
To avoid this kind of error, never use raw types, instead prefer generic types. You want a List
of Integers?
Try this:
int ar[] = {1,2,3};
List<Integer> arList = Arrays.asList(ar); // here
arList.set(1,8);
The compiler will show an error in the line where I wrote the comment, indicating that this will not work. When ar
is a primitive array, int[]
in your case, then Arrays.asList(ar)
will return a List<int[]>
. List<int[]>
and List<Integer>
are not compatible. What you have right now is a List
of int[]
with 1 entry (at index 0), being your array.
As mentioned before, if you change from primitive int ar[] = {1,2,3};
to object Integer ar[] = {1,2,3};
it will work, because the return type of Arrays.asList(ar)
will be List<Integer>
.
The reason of the specified behavior is clear, but there is nothing about this situation in the javadoc for the Arrays.asList() and no check was made for the primitive arrays as input parameters. So, I think this should be treated like a bug.
Method javadoc:
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with {@link Collection#toArray}. The returned list is erializable and implements {@link RandomAccess}.
This method also provides a convenient way to create a fixed-size list initialized to contain several elements