//class doesn't do much than just gets the title of the book
public class BookLibrary {
String title;
public BookLibrary(){}
public void setTitle( String names) {
title = names;
}
public String getTitle(){
return title;
}
}
这是我的代码,用于从arraylist中删除对象 公共类LibraryAssistant {
ArrayList<BookLibrary> booklib = new ArrayList<>();
int numOfBooks = 0;
public void setupLibrary(){
BookLibrary bc = new BookLibrary();
bc.setTitle("fantastic beasts and where to find them");
BookLibrary bc1 = new BookLibrary();
bc1.setTitle("Harry potter and the prisoner of azkabans");
BookLibrary bc2 = new BookLibrary();
bc2.setTitle("one day for the thief");
booklib.add(bc);
booklib.add(bc1);
booklib.add(bc2);
numOfBooks++;
for(BookLibrary book : booklib){
System.out.println(book.getTitle());
}
}
public void borrowbook(){
while(!booklib.isEmpty()){
String getbooknum = userInput("please enter a book number of the book you want to borrow");
int index = Integer.parseInt(getbooknum);
if(index>=0){
booklib.remove(index);
for(BookLibrary lb : booklib){
System.out.println(lb.getTitle());
}
}
numOfBooks--;
} if(booklib.isEmpty()){
System.out.println("the library is empty");
}
}
答案 0 :(得分:1)
IndexOutOfBoundException背后的原因是每次删除对象时arraylist的大小都会减小。因此,如果您从书中删除第一个标题(索引0),则列表的大小将为2。当用户进行第二次删除(索引1)时,它将正常工作。但是,当用户要进行第三次移除(索引2)时,由于ArrayList的大小现在为1,它将抛出IndexOutOfBoundException。
答案 1 :(得分:0)
我的第一个观察结果是setUpLibrary()中的numOfBooks应该设置为3,或者应该更新为数组列表的大小。 第二个观察结果是在borrowbook()中,while循环运行直到bookLib为空。因此,行booklib.remove(index);没有更多元素或用户指定的数字超出范围时,将抛出错误IndexOutOfBoundsException。
请参考以下文档: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(int)