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?
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With