Skip to content
Advertisement

IndexOutOfBoundException when creating an Array from a List [closed]

I have this method that returns a List of usernames, and for some reason it is throwing an indexOutOfBoundException.

public  String [] getUsernames(){
    String[] usernames = new String [friendRequests.size()];
    int i = 1;
    for (FriendRequest  friendRequest:  this.friendRequests){
        usernames[i]= friendRequest.getUsername();
        i++;
    }
    return usernames;
}

Advertisement

Answer

array index starts from 0

and you started from 1, so it would lead to ArrayIndexOutOfBoundException

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement