Java – when using “. Get (0)” in an empty list, I get an out of bounds exception instead of null?
•
Java
So in my homework, for my error checking test, I made a list < someobject > and I got an indexoutofboundsexception I passed the examination Isempty to solve it, but I wonder why not:
boolean b = myList.Get(0) != null;
Work?
When I debug the application and look at mylist, I see nine null entries I can see that its size is 0, so why is this possible? Its size is 0, so it doesn't exist when I try to get an entry?
Solution
If Java:
ArrayList<Object> list = new ArrayList<Object>(); list.get(0);
Will trigger
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 the source code Rangecheck may be checking that what you want is less than the size of the list If it's higher then
throw new indexoutofboundsexception();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码