I have a ShoppingCart app that can add/remove Book objects
A book has an isbn attribute.
I need to check if someone has added a duplicate copy of same book to the cart
ie,
Book b1 = new Book("isbn222");
Book b2 = new Book("isbn222");
Book b3 = new Book("isbn333");
Book b4 = new Book("isbn444");
Book b5 = new Book("isbn444");
Book b6 = new Book("isbn444");
Book b7 = new Book("isbn555");
//add these to cart
In this case I want to generate a warning to the user that duplicates 2 copies with isbn222, three copies with isbn444 are added.
I thought of creating a CartValidator as below,However,I couldn’t implement the logic given below..How do you create sub lists in java?
Any help regarding this much appreciated.
thanks
mark.
public class CartValidator {
public static String validate(ShoppingCart<Book> cart) {
StringBuffer warning = new StringBuffer("duplicates");
List<Book> items = cart.getItems();
/*
* take first item from list, temp= items.get(0)
* check against all the rest for duplicates and build warning compare with item1,item2..
* take second item temp= items.get(1)
* check against all the rest for duplicates and build warning compare with item2,item3..
*/
return warning.toString();
}
I would suggest to have Map with
<String, List<Book>>. where String key the Book ISBN and the list is the books with the ISBN.