Win a copy of Java 9 Revealed this week in the Features new in Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Negative index for ArrayList element leading to ArrayIndexOutOfBoundsException?  RSS feed

 
Shane Jensen
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,

It was my understanding that trying to access a non-existing ArrayList element leads to an IndexOutOfBoundsException, while trying to access a non-existing Array element leads to an ArrayIndexOutOfBoundsException.

When I try to run the following code, an IndexOutOfBoundsException indeed is thrown.


However, when I use a negative index, an ArrayIndexOutOfBoundsException is thrown.

What is the logic behind this? It would make a lot more sense to me if trying to access any non-existing element of an ArrayList would throw the same exception.

Thank you in advance!

Regards,
Shane
 
Charles O'Leary
Ranch Hand
Posts: 167
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for that question.  I noticed that too.  Now, I finally looked into it.   

Long story short: It's kinda like the difference between NumberFormatException and IllegalArgumentException: Namely, the child class is a larger object (is more specific) than its parent
2017-06-18_20-48-07.png
[Thumbnail for 2017-06-18_20-48-07.png]
 
Shane Jensen
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Charles,

Thanks again!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!