防止Java

时间:2015-12-09 16:03:58

标签: java arraylist compare

我在Book类中设置了一个构造函数,另一个类我已经设置了一个类型为Book的ArrayList。该书预计会收到titleauthorbookIDcopiestimesLoanedonLoan

我希望找到最有效的方法来确保在添加图书之前没有重复的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 个答案:

答案 0 :(得分:1)

我还建议使用Map,但是如果你想使用ArrayList,你应该认为ArrayList实现了List接口,它有一个contains方法。因此,您可以只查询您的ArrayList是否包含新书。然后,contains方法将使用equals方法遍历ArrayList,以检查每本书是否等于您要比较的新书。 (以正确方式)以安全的方式覆盖您的Book的HashCode是个好主意。