开发者

duplicate item allowed in shopping cart but need warning msg

I have a ShoppingCart app that can add/remove Book objects A book has an isbn attribute. I need to check if 开发者_C百科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.


Well if you don't want several warnings for the same ISBN you either a) sort the input and then check it (simple loop) or b) check your output to make sure it doesn't already contains a warning of the given ISBN.

From a performance point of view the sorting should be better (O(n log n + n) vs. O(n^2)) and you also don't need extra memory for a hashtable or something.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜