【发布时间】:2014-04-15 01:04:36
【问题描述】:
我有一个存储在文件中的用户列表,当我想向用户添加参数时,我
ArrayList<User> list = loadListFromfile();
System.out.println("USER LIST: "+ list);
//the user to update
User oldUser = getCurrentUser();
System.out.println("CURRENT USER: "+ oldUser);
//update user receives an user and an update param and returns the updated user
User newUser = updateUser(oldUser, "updateparam");
System.out.println("NEW USER: "+ newUser);
//replace the old user with the new one
list.set(list.indexOf(oldUser), newUser);
所有打印都返回正确的值,但是当我调用时
list.set(list.indexOf(oldUser), newUser);
应用程序因此错误而崩溃
java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
这真的很奇怪,我无法理解问题的原因,此外列表只有 2 项(不是 12 项)。
我该如何解决这个问题?
【问题讨论】:
-
但在这种情况下,列表不为空,并且 println 会正确打印所有值...所以我真的不明白为什么会出现此错误
-
哎呀,我的错..您的列表确实不为空..但是您的
oldUser的索引无效..您确定oldUser在列表中..?也许只是空白或什么的问题..? -
因为
oldUser不在list内
标签: java android indexoutofboundsexception