Exception when working with List collections

  • 3
  • Locked
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.
You can't complete this task, because you're not signed in.
Comments (5)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Nirali Rawal
Level 15 , Hopewell, United States
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
Level 41
2 October 2019, 06:04
Because after initialization
ArrayList<String> list = new ArrayList();
list doesn't have element with index == 18
Level 41 , Madrid, Spain
2 December 2020, 12:19
I'm not sure but I guess It's because
ArrayList list = new ArrayList();
creates an ArrayList with default size 10 and the index 18 is out of that array. Can anyone confirm this?
Level 15 , Old Town, United States
8 May 2021, 14:04
That was my thought
Level 10 , Dresden, Germany
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.