I want to see if two objects in the same array list are the same. Similarly if there are not objects that are the same in the array list I also want to display an appropriate message. At the moment it is printing too much. I just want it to display one line: "there are books that are the same" or "there are NO books that are the same". Here are my efforts so far.
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");
}
}
}
Thanks in advance.
EDIT: I amended my code as such according to "duplicate question"
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");
}
Still prints "there are duplicates" when there clearly are not.
RESOLVED: Ordering of my code was incorrect. Solution-
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");
}
elsewon't help if it's inside the loop. You need to set a variable. I'm not sure what you think it's not a duplicate.setOfBookstoo early. You need to do it after your list is populated.