当我调用这个方法时,为什么我的数组列表越界(索引 3,大小 3) [英] why is my arraylist out of bounds (index 3, size 3) when I call this method

查看:43
本文介绍了当我调用这个方法时,为什么我的数组列表越界(索引 3,大小 3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用书名在书籍数组列表中查找一本书.当我尝试添加不在 book 数组列表中的书籍时,它给了我 arrayoutofbounds 异常 index:3, size:3.... 我该如何解决?

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

推荐答案

您不必在这里使用索引,只需遍历您的数组列表.

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

这篇关于当我调用这个方法时,为什么我的数组列表越界(索引 3,大小 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆