By the ninth level, we've already got some idea of List collections, and exceptions. Let's bring this knowledge together: catch exceptions when executing the following code: ArrayList<String> list = new ArrayList<String>(); String s = list.get(18); Catch and display the exception on the screen, indicating its type.
Exception when working with List collections
- 3
Locked
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
Nirali Rawal
1 October 2019, 15:22
Why exactly does this have an IndexOutofBoundsException? I thought in a list we can add as many values as possible, hence I'm not sure why the IndexOutofBoundException
+1
Roman
2 October 2019, 06:04
Because after initialization
list doesn't have element with index == 18 +1
Isma
2 December 2020, 12:19
I'm not sure but I guess It's because
creates an ArrayList with default size 10 and the index 18 is out of that array.
Can anyone confirm this? +1
ImDevin
8 May 2021, 14:04
That was my thought
+1
Michael
28 August 2021, 07:47
The list does not have elements, when it is initialized. So, accessing index 18 gets an IndexOutOfBoundsException because this index does not exist.
I also thought about the question, why it does not throw an ArrayIndexOutOfBoundException. The reason is because ArrayList is part of Java's collection framework and implements Java's List interface. ArrayIndexOutOfBoundExceptions are only triggered with arrays (and not collections) when an index is addressed which does not exist. This distinction shows how specific the exception handling in Java is.
0