gpt4 book ai didi

ArrayList 上出现 java.lang.IndexOutOfBoundsException

转载 作者:太空狗 更新时间:2023-10-29 16:20:12 25 4
gpt4 key购买 nike

CopyOnWriteArrayList<Options> Options= new CopyOnWriteArrayList<Options>();
Options Options = Options.get(selectedFilterIndex);

我在上面一行中收到错误。选项是一个 ArrayList。我尝试使用 ArrayList 以及 CopyOnWriteArrayList,但出现以下错误。如何处理此类异常。

06-21 15:28:23.257: E/XXX(8985): Uncaught exception is: 
06-21 15:28:23.257: E/XXX(8985): java.lang.RuntimeException: An error occured while executing doInBackground()
06-21 15:28:23.257: E/XXX(8985): at android.os.AsyncTask$3.done(AsyncTask.java:278)
06-21 15:28:23.257: E/XXX(8985): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-21 15:28:23.257: E/XXX(8985): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-21 15:28:23.257: E/XXX(8985): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-21 15:28:23.257: E/XXX(8985): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-21 15:28:23.257: E/XXX(8985): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
06-21 15:28:23.257: E/XXX(8985): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
06-21 15:28:23.257: E/XXX(8985): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
06-21 15:28:23.257: E/XXX(8985): at java.lang.Thread.run(Thread.java:856)
06-21 15:28:23.257: E/XXX(8985): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
06-21 15:28:23.257: E/XXX(8985): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
06-21 15:28:23.257: E/XXX(8985): at java.util.ArrayList.get(ArrayList.java:304)
06-21 15:28:23.257: E/XXX(8985): at com.usercontext.CommonActivity$6.doInBackground(AppointmentsActivity5.java:354)
06-21 15:28:23.257: E/XXX(8985): at com.usercontext.CommonActivity$6.doInBackground(AppointmentsActivity5.java:1)
06-21 15:28:23.257: E/XXX(8985): at android.os.AsyncTask$2.call(AsyncTask.java:264)
06-21 15:28:23.257: E/XXX(8985): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

最佳答案

你不应该处理这个异常 - 你应该编写一开始就不会导致它的代码。

您刚刚创建了一个空列表 - 没有可以传递给 get 的值,后者将返回一个值。该列表的大小为 0,索引意味着大于或等于 0,并且严格小于该大小。

此外,如果您遵循 Java 变量命名约定 camelCased,您的代码将更易于阅读 - 这将避免两个变量具有相同的名称和一个类型。还要避免两次使用相同的变量名...

CopyOnWriteArrayList<Options> allOptions = new CopyOnWriteArrayList<Options>();
// This will still fail for any value of selectedFilterIndex, as the list
// is empty... but at least it's easier to understand.
Options selectedOptions = allOptions.get(selectedFilterIndex);

关于ArrayList 上出现 java.lang.IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17232856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com