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

我在上面的行中收到错误。选项是一个 ArrayList。我尝试了ArrayListas well 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)
4

2 回答 2

5

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

您刚刚创建了一个空列表 -没有可以传递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);
于 2013-06-21T10:22:57.130 回答
1

您刚刚声明了List,其中还没有任何元素。

CopyOnWriteArrayList<Options> Options= new CopyOnWriteArrayList<Options>();

而你正试图get()List没有元素。ArrayList内部将使用数组缓冲区来存储元素。根据 Javadoc get(int index)

抛出:

IndexOutOfBoundsException - 如果索引超出范围 (index < 0 || index >= size())

因此Options.get(selectedFilterIndex);仅适用于(selectedFilterIndex>-1 && selectedFilterIndex < Options.size())

于 2013-06-21T10:22:39.673 回答