16
16
*/
17
17
package sessions ;
18
18
19
- import java .util .ArrayList ;
20
19
import java .util .Collections ;
21
- import java .util .List ;
20
+ import java .util .HashSet ;
21
+ import java .util .Set ;
22
22
23
23
public class DummyCart {
24
- final List <String > items = Collections .synchronizedList (new ArrayList <>());
24
+ final Set <Item > items = Collections .synchronizedSet (new HashSet <>());
25
+ int itemId = -1 ;
25
26
String submit = null ;
26
- String item = null ;
27
27
28
- private void addItem ( String name ) {
29
- items . add ( name ) ;
28
+ public void setItemId ( int itemId ) {
29
+ this . itemId = itemId ;
30
30
}
31
31
32
- private void removeItem (String name ) {
33
- items . remove ( name ) ;
32
+ public void setSubmit (String s ) {
33
+ submit = s ;
34
34
}
35
35
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
+ }
38
42
}
39
43
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
+ }
42
50
}
43
51
44
- public String [] getItems () {
45
- return items .toArray (new String [0 ]);
52
+ public Item [] getItems () {
53
+ return items .toArray (new Item [0 ]);
46
54
}
47
55
48
56
public void processRequest () {
49
57
// null value for submit - user hit enter instead of clicking on
50
58
// "add" or "remove"
51
59
if (submit == null || submit .equals ("add" )) {
52
- addItem (item );
60
+ addItem (itemId );
53
61
} else if (submit .equals ("remove" )) {
54
- removeItem (item );
62
+ removeItem (itemId );
55
63
}
56
64
57
65
// reset at the end of the request
@@ -61,6 +69,6 @@ public void processRequest() {
61
69
// reset
62
70
private void reset () {
63
71
submit = null ;
64
- item = null ;
72
+ itemId = - 1 ;
65
73
}
66
74
}
0 commit comments