DataKeeper.java
01 /*
02  *
03  * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
04  *
05  */
06 package demo.townsend.service;
07 
08 import java.util.ArrayList;
09 import java.util.Iterator;
10 import java.util.List;
11 
12 /**
13  * DataKeeper keeps track of the current state of the user's list. All
14  * modifications to the user's list are made by calling DataKeeper's methods.
15  */
16 public class DataKeeper implements java.io.Serializable {
17    private static final long serialVersionUID = 5262292781659376986L;
18    private final int MAX_NUM = 5;
19    private final ArrayList<Product> userList;
20 
21    public DataKeeper() {
22       userList = new ArrayList<Product>();
23    }
24 
25    public void addListItem(Product newProd) {
26       for (Iterator<Product> iter = userList.iterator(); iter.hasNext();) {
27          if (iter.next().getId().equals(newProd.getId())) {
28             iter.remove();
29          }
30       }
31 
32       userList.add(0, newProd);
33 
34       if (userList.size() > MAX_NUM) {
35          userList.remove(MAX_NUM);
36       }
37    }
38 
39    public int getListSize() {
40       return userList.size();
41    }
42 
43    public List<Product> getList() {
44       return userList;
45    }
46 
47    public Product getCurrent() {
48       if (getListSize() 0) {
49          return userList.get(0);
50       }
51       return null;
52    }
53 
54    @Override
55    public String toString() {
56       StringBuilder sb = new StringBuilder();
57       boolean startedSeps = false;
58       for (Iterator<Product> iter = getList().iterator(); iter.hasNext();) {
59          if (startedSeps) {
60             sb.append(", ");
61          else {
62             startedSeps = true;
63          }
64          sb.append(iter.next().toString());
65       }
66       return sb.toString();
67    }
68 }