1616 */
1717package sessions ;
1818
19- import java .util .ArrayList ;
2019import java .util .Collections ;
21- import java .util .List ;
20+ import java .util .HashSet ;
21+ import java .util .Set ;
2222
2323public class DummyCart {
24- final List <String > items = Collections .synchronizedList (new ArrayList <>());
24+ final Set <Item > items = Collections .synchronizedSet (new HashSet <>());
25+ int itemId = -1 ;
2526 String submit = null ;
26- String item = null ;
2727
28- private void addItem ( String name ) {
29- items . add ( name ) ;
28+ public void setItemId ( int itemId ) {
29+ this . itemId = itemId ;
3030 }
3131
32- private void removeItem (String name ) {
33- items . remove ( name ) ;
32+ public void setSubmit (String s ) {
33+ submit = s ;
3434 }
3535
36- public void setItem (String name ) {
37- item = name ;
36+ private void addItem (int itemId ) {
37+ try {
38+ items .add (Item .values ()[itemId ]);
39+ } catch (ArrayIndexOutOfBoundsException e ) {
40+ // Ignore. Can only happen if user edits URL directly.
41+ }
3842 }
3943
40- public void setSubmit (String s ) {
41- submit = s ;
44+ private void removeItem (int itemId ) {
45+ try {
46+ items .remove (Item .values ()[itemId ]);
47+ } catch (ArrayIndexOutOfBoundsException e ) {
48+ // Ignore. Can only happen if user edits URL directly.
49+ }
4250 }
4351
44- public String [] getItems () {
45- return items .toArray (new String [0 ]);
52+ public Item [] getItems () {
53+ return items .toArray (new Item [0 ]);
4654 }
4755
4856 public void processRequest () {
4957 // null value for submit - user hit enter instead of clicking on
5058 // "add" or "remove"
5159 if (submit == null || submit .equals ("add" )) {
52- addItem (item );
60+ addItem (itemId );
5361 } else if (submit .equals ("remove" )) {
54- removeItem (item );
62+ removeItem (itemId );
5563 }
5664
5765 // reset at the end of the request
@@ -61,6 +69,6 @@ public void processRequest() {
6169 // reset
6270 private void reset () {
6371 submit = null ;
64- item = null ;
72+ itemId = - 1 ;
6573 }
6674}
0 commit comments