Java Reference
In-Depth Information
7. expressionA.interpret(c);
8. expressionB.interpret(c);
9. Object exprAResult = c.get(expressionA);
10. Object exprBResult = c.get(expressionB);
11. if ((exprAResult instanceof String) && (exprBResult instanceof String)){
12. if (((String)exprAResult).indexOf((String)exprBResult) != -1){
13. c.addVariable(this, Boolean.TRUE);
14. return;
15. }
16. }
17. c.addVariable(this, Boolean.FALSE);
18. return;
19. }
20. }
The Context class represents shared memory for expressions during evaluation. Context is a wrapper around a
HashMap . In this example, the Expression objects provide the keys for the HashMap , and the results of calling the
interpret method are stored as its values.
Example A.60 Context.java
1. import java.util.HashMap;
2. public class Context{
3. private HashMap map = new HashMap();
4.
5. public Object get(Object name){
6. return map.get(name);
7. }
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 A.61 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.
Search WWH ::




Custom Search