Yah, I was having a bad day when I posted.
Maybe I'm still having one.
Part of this is me not being a very good architect.
I want to code the simplest possible Cart. Cart contains LineItem. LineItems contains a Product. And I'm hoping to use Collection classes as much as possible.
Product has all the usual things like name, price, size, colour, etc. It also contains variable (custom) data for each Product. So it's not a typical product in a normal Amazon sense. When you order one of our Products, you get a form to fill out. This data should be retained in the cart so that it can be edited.
LineItem basically contains a Product a quantity and a line discount.
Cart contains LineItems, plus methods to calculate the cart total.
So far alright, because that's all just talk. Implementation has always been my problem.
Unlike a real-life Safeway shopping cart, my cart has at very least the implied order of insertion. But simple indexing will not work, because if I check off the first three cart items, and click 'delete' (on a cart summary
jsp page, for example), I can't just say:
cart.remove(0);
cart.remove(1);
cart.remove(2);
This would remove the 1st, 3rd and 5th items.
So the "line number" can't change with addition and deletion of items. So ArrayList (whose index changes) is out, right? (OR else I can only delete one thing at a time).
I'm not sure why, but TreeSet appealed to me, because it had order and didn't have that index trouble. I could implement Comparable (my 'number' would do the ordering). And then I could use the object remove() method, by creating a blank LineItem object (with no Product) like:
cart.remove(new LineItem(0));
etc, etc...
Which is why (Jason) this wouldn't be the case:
"If you already had a reference to Object o, why would you need to get it from the Set?"
I didn't "really" have the object, but I had stupidly overriden LineItem's equals() method to only compare the 'number'. It was kinda cool, but I think in the end, stupid.
I think Frank has the right idea, but for right now I'm stuck with 1.3.1, which doesn't have the LinkedHashMap.
For now, i'm using ArrayList and just don't have anything that deletes more than one object at at a time.
Background: "We need this web site change done in two days.. there are no specs.. GO!" . That was Thursday around 11am. Both myself and the senior developer wanted to start moving towards a 'better' version of our site, rather than constantly 'patching' the old one, and we had already done preliminary head-space stuff about Products, Carts, etc, etc. So it was super-crunch time, and of course, nothing concrete had been thought about. The idea of the Cart was cool (currently we use a
String[] for the cart, no objects at all), but we hadn't thought about it too deeply.