Java Reference
In-Depth Information
8.
9. public void addVariable(Object name, Object value) {
10. map.put(name, value);
11. }
12. }
With this series of expressions, it is possible to perform fairly sophisticated comparisons. ContactList holds a
series of contacts in this example. It defines a method called getContactsMatchingExpression , which
evaluates the Expression for every Contact and returns an ArrayList .
Example 2.18 ContactList.java
1. import java.io.Serializable;
2. import java.util.ArrayList;
3. import java.util.Iterator;
4. public class ContactList implements Serializable {
5. private ArrayList contacts = new ArrayList();
6.
7. public ArrayList getContacts() {
return contacts;
}
8. public Contact[] getContactsAsArray() {
return (Contact [])(contacts.toArray(new Contact [1]));
}
9.
10. public ArrayList getContactsMatchingExpression(Expression expr, Context ctx, Object key) {
11. ArrayList results = new ArrayList();
12. Iterator elements = contacts.iterator();
13. while (elements.hasNext()) {
14. Object currentElement = elements.next();
15. ctx.addVariable(key, currentElement);
16. expr.interpret(ctx);
17. Object interpretResult = ctx.get(expr);
18. if ((interpretResult != null) && (interpretResult.equals(Boolean.TRUE))) {
19. results.add(currentElement);
20. }
21. }
22. return results;
23. }
24.
25. public void setContacts(ArrayList newContacts) {
contacts = newContacts;
}
26.
27. public void addContact(Contact element) {
28. if (!contacts.contains(element)) {
29. contacts.add(element);
30. }
31. }
32. public void removeContact(Contact element) {
33. contacts.remove(element);
34. }
35.
36. public String toString() {
37. return contacts.toString();
38. }
39. }
With the Expression hierarchy and the ContactList , it is possible to perform database-like queries for the
Contacts in a ContactList . For example, you could search for all those Contacts with a title containing the
characters “Java” by doing the following:
Create a ConstantExpression with the string “Java”.
Create a VariableExpression with the target object and the string “getTitle”.
Create a ContainsExpression with the VariableExpression as the first argument and the
ConstantExpression as the second.
Pass the ContainsExpression into a ContactList object's getContactsMatchingExpression method.
Search WWH ::




Custom Search