public class PrivateList
2: import java.util.ArrayList;
3: import java.util.List;
4: import java.util.Collections;
6: /**
7: * A class to demonstrate the non-safe and safe ways of returning a List to
8: * client programs. The object remembers words entered by the user, but rejects
9: * nulls and words starting with the letter F (upper- or lower-case). Words
10: * can't be removed after they've been added.
11: *
12: * getWordsUnsafe() returns a reference to the List, allowing the client to
13: * mess with its contents -- VIOLATING our contract.
14: *
15: * getWordsCopy() returns a copy of the list, keeping us safe from the client,
16: * at the cost of doing a copy.
17: *
18: * getWordsSafe() returns our list wrapped in an unmodifiable list object,
19: * keeping us safe from the client without having to make a copy.
20: *
21: * @author Mark Young (A00000000)
22: */
23: public class PrivateList {
25: private final List<String> myWords;
27: /**
28: * Create a new, empty list.
29: */
30: public PrivateList() {
31: myWords = new ArrayList<>();
32: }
34: /**
35: * Add the given word to this list. Reject nulls and words starting with F
36: * (whether lower-case or upper-case).
37: *
38: * @param newWord the word to add.
39: * @return true if the word was added; false otherwise.
40: */
41: public boolean addWord(String newWord) {
42: // don't allow nulls or f-words
43: if (newWord == null || newWord.toUpperCase().startsWith("F")) {
44: return false;
45: }
46: myWords.add(newWord);
47: return true;
48: }
50: /**
51: * Return the list of words -- IN AN UNSAFE WAY! This method violates
52: * encapsulation by allowing the client to add nulls or F-words, or remove
53: * words that were previously added.
54: *
55: * @return the List of words.
56: */
57: public List<String> getWordsUnsafe() {
58: // bad version
59: return myWords;
60: }
62: /**
63: * Return the list of words -- IN A SAFE WAY! This method ensure that our
64: * encapsulation works by returning a COPY of our List. Any changes the
65: * client makes will be to that copy, and not our original.
66: *
67: * @return the List of words.
68: */
69: public List<String> getWordsCopy() {
70: return new ArrayList<>(myWords);
71: }
73: /**
74: * Return the list of words -- IN A SAFE WAY! This method ensure that our
75: * encapsulation works by returning a List that the client can't modify at
76: * all.
77: *
78: * @return the List of words.
79: */
80: public List<String> getWordsSafe() {
81: return Collections.unmodifiableList(myWords);
82: }
84: /**
85: * Create a String representation of this List.
86: *
87: * @return a String representing this List.
88: */
89: @Override
90: public String toString() {
91: return myWords.toString();
92: }
94: }