java 在空列表上使用“.Get(0)”时,我得到一个越界异常而不是空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14636204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:55:09  来源:igfitidea点击:

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

javaarraylistindexoutofboundsexception

提问by RaenirSalazar

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 .isEmptybut what I would like to know why doesn't:

所以在我的家庭作业中,对于我的错误检查测试,我做了一个 get on aList<SomeObject>并且我得到了IndexOutOfBoundsException. 我通过使用检查来解决它,.isEmpty但我想知道为什么不:

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

work?

工作?

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

当我调试应用程序并查看时,myList我看到null. 我可以将其视为大小0,所以这可能是为什么?它是 size 0,所以当我尝试获取它不存在的条目时?

回答by wtsang02

If it is Java:

如果是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

原因其实在源代码上。rangecheck 可能正在检查您尝试获取的内容是否小于列表的大小。如果它更高那么

throw new IndexOutOfBoundsException();

回答by user207421

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.

按设计工作。我不明白为什么您希望能够null从空的List. 你不能。