问题
I'm trying to find a book in an arraylist of books by using the book's name. When I try to add a book that's not in the book arraylist, it gives me the arrayoutofbounds exception index:3, size:3.... how can I fix that ?
public Book findBookByName(String bookNameToFind)
{
boolean found = false;
String bookName;
int index = 0;
while(!found)
{
bookName = bookLibrary.get(index).getTitle();
if(bookName.equals(bookNameToFind))
{
found = true;
}
else
{
index++;
}
}
return bookLibrary.get(index);
回答1:
You don't have to use index here and just iterate through your arraylist.
I inverted equals because don't know if title of the book is mandatory in your model.
public Book findBookByName(String bookNameToFind) {
for (Book book : bookLibrary) {
if (bookNameToFind.equals(book.getTitle()))
return book;
}
return null;
}
回答2:
Try a for loop:
public Book findBookByName(String bookNameToFind)
{
for (int i = 0; i < bookLibrary.Count(); i++) {
if (bookLibrary.get(i).getTitle().equals(bookNameToFind))
return bookLibrary.get(i);
}
return null;
}
回答3:
Well, if you don't find the book, then your index is going to run off the end of the list. You can either do the for loop like sanghas26 suggested (which is the best solution), or you can add a check at the beginning of the loop to see if i
has gone too far.
来源:https://stackoverflow.com/questions/26044242/why-is-my-arraylist-out-of-bounds-index-3-size-3-when-i-call-this-method