如何检查ArrayList中的两个对象是否相同?

时间:2017-11-01 07:14:55

标签: java loops arraylist boolean

我想看看同一个数组列表中的两个对象是否相同。同样,如果数组列表中没有相同的对象,我也想显示适当的消息。目前它打印太多了。我只是希望它显示一行:“有相同的书”或“没有相同的书”。到目前为止,这是我的努力。

public static void main(String[] args) {

    List<Book> listOfBooks = new ArrayList<>();
    Book book1 = new Book();
    Book book2 = new Book();
    Book book3 = new Book();

    listOfBooks.add(book1);
    listOfBooks.add(book2);
    listOfBooks.add(book3);
    listOfBooks.add(book2);

    for (Book bookA : listOfBooks) {
        for (Book bookB : listOfBooks) {
            if (bookA.equals(bookB)) {
                System.out.println("there are books that are the same");
            }
            System.out.println("there are NO books that are the same");
        }

    }
}

提前致谢。

编辑:我根据“重复问题”修改了我的代码

List<Book> listOfBooks = new ArrayList<>();
    Set<Book> setOfBooks = new HashSet<Book>(listOfBooks);

    Book book1 = new Book();
    Book book2 = new Book();
    Book book3 = new Book();

    listOfBooks.add(book1);
    listOfBooks.add(book2);
    listOfBooks.add(book3);

    if (setOfBooks.size() < listOfBooks.size()) {
        System.out.println("there are duplicates");
    } else {
        System.out.println("there are no duplicates");
    }

当显然没有时,仍打印“有重复”。

已解决:我的代码订购不正确。溶液 -

    List<Book> listOfBooks = new ArrayList<>();

    Book book1 = new Book();
    Book book2 = new Book();
    Book book3 = new Book();

    listOfBooks.add(book1);
    listOfBooks.add(book2);
    listOfBooks.add(book3);

    Set<Book> setOfBooks = new HashSet<>(listOfBooks);

    if (setOfBooks.size() < listOfBooks.size()) {
        System.out.println("there are duplicates");
    } else {
        System.out.println("there are no duplicates");
    }

0 个答案:

没有答案