arraylist防止Java中重复的ID条目
我在Book
类中设置了构造函数,在另一个类中设置了Book
类型的ArrayList。这本书预计会收到{onLoan
等
我正在寻找一种最有效的方法来确保在添加一本书之前没有重复的bookID
。我还没有了解Map
等,所以现在想避免这种情况。我在考虑在添加之前使用for循环检查bookID's
下面是我的addBook方法:
// Adding a book to ArrayList
public void addBook(){
System.out.println("==============================");
// Getting user input and assigns it to variables
System.out.print("Enter a title: ");
String title = sc.nextLine();
System.out.print("Enter an author: ");
String author = sc.nextLine();
System.out.print("Enter quantity of books: ");
int quantity = checkInput(sc); // checks for valid integer
// Generates random ID for book
int bookID = (int) Math.round(Math.random() * 1000000);
// Adding book the the ArrayList, using user input taken above
newBook.add(new Book(title, author, bookID, quantity, 0, false));
// Adding to maxReturns for returnBook()
maxReturns.add(quantity);
// Testing that it has added - TAKE OUT AFTER COMPLETION
for(int i = 0; i < newBook.size(); i++){
System.out.println(newBook.get(i).getBookID() + " " + newBook.get(i).getTitle());
}
// Showing its been added
System.out.println("Book has been added!");
System.out.println("==============================");
}
# 1 楼答案
我还建议使用一个映射,但是如果你想使用ArrayList,你应该认为ArrayList实现了List接口,它有一个contains方法。因此,您可以直接查询ArrayList是否包含新书。然后,contains方法将使用equals方法在ArrayList中循环,以检查每本书是否与要比较的新书相同。以一种安全的方式(正确地)覆盖你的书的哈希代码是个好主意