Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using ".Get(0)" on an empty list, I get an out of bounds exception and not null?

So in my homework assignment, for my error checking testing stuff I do a get on a List<SomeObject> and I get an IndexOutOfBoundsException. I solve it by using a check on .isEmpty but what I would like to know why doesn't:

boolean b = myList.Get(0) != null;

work?

When I debug the application and look at myList I see 9 entries of null. I can see it as being size 0 though, so that's probably why? It's size 0, so when I try to get an entry it doesn't exist?

like image 298
RaenirSalazar Avatar asked Jan 31 '13 22:01

RaenirSalazar


2 Answers

If it is Java:

ArrayList<Object> list = new ArrayList<Object>();
list.get(0);

will cause

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    at java.util.ArrayList.get(ArrayList.java:322)
    at HelloWorldTester.main(HelloWorldTester.java:7)

The reason is actually on the source code. rangecheck is probably checking if what you are trying to get is lower than the size of the list. If it is higher then

throw new IndexOutOfBoundsException();
like image 177
wtsang02 Avatar answered Sep 28 '22 02:09

wtsang02


Working as designed. I don't understand why you expect to be able to get anything, even null, from an empty List. You can't.

like image 30
user207421 Avatar answered Sep 28 '22 03:09

user207421