Вопрос

I have a user list stored on a file, when I want to add a parameter to the user I

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);

All the prints returns correct values but when I invoke

list.set(list.indexOf(oldUser), newUser);

The app crashes with this error

java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1

This is really strange and I cannot understand the reason of the issue, in addition list has only 2 items (not 12).

How could I fix this?

Это было полезно?

Решение

indexOf(oldUser) returns -1 if the oldUser is not found. In that case, set(-1) will throw ArrayIndexOutOfBoundsException.

Другие советы

You should add the oldUser to the list. The error information shows that the oldUser doesn't exist in the list. Please add

list.add(oldUser);

The problem appears to be that list.indexOf(oldUser) is returning -1, which is in fact an array index out of bounds. How do you obtain oldUser? Could we get the code on getCurrentUser()?

Also, any chance that updateUser(oldUser, "updateparam") is messing up with the list? It should work whether it returns a pointer to a new user or a pointer to the old user (the same pointer you're passing in the first argument), and it should work whether it modifies the actual object pointed at by oldUser parameter or not.

Basically I fear you might be facing an issue with oldUser.equals(e) for every e contained in the list which is called in the contains method of ArrayList. But can't really say without the code. You might find it with this idea though.

oldUser is not coming as -1, but it is not present in the list. That's why its throwing ArrayIndexOutOfBoundsException.
As per code System.out.println("CURRENT USER: "+ oldUser); it will not print -1.

Update:

 list.indexOf(oldUser) // Returning -1.

Here index of oldUser in list returns the index at which the value of oldUser present. The actual value of oldUser is not present in your list, that's why its returning -1.

list.set(-1, newUser);

When it try to set anything in -1 location, its throwing ArrayIndexOutOfBoundsException.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top