Working with multiple objects A variable can refer to a single object: IBehavior cc = new ColorChanging(); IBehavior br = new Breathing(); A variable referring to many objects? No, but we saw how to build a composite object. IBehavior cc = new CompositeBehavior(cc,br); But it’s not too easy to add/remove items from a composite. Are there options?
Collections interface: java.util.Collection classes: –java.util.HashSet –java.util.ArrayList E is the type of element contained in the collection
Using a Collection (HashSet ) HashSet names = new HashSet (); names.add(“Amy”);names.remove(“Bob”); names.add(“Bob”); names.add(“Cindy”); names.add(“Dave”); names.add(“Emma”); …
for-each loop (w/HashSet ) for (String name : names) { System.out.println(name); } This prints out the following in the console window: Amy Cindy Dave Emma
Collections.shuffle Collections.shuffle(List ) The shuffle method randomizes the order of elements in the collection it is passed. The collection passed to shuffle must be a List: a collection which maintains items in some order.
Using a Collection (ArrayList ) ArrayList names2 = new ArrayList (); names2.add(“Amy”);names2.remove(“Bob”); names2.add(“Bob”); names2.add(“Cindy”); names2.add(“Dave”); names2.add(“Emma”); …
for-each loop (w/ArrayList ) for (String name : names2) { System.out.println(name); } This prints out the following in the console window: Amy Cindy Dave Emma
shuffling… Collections.shuffle(names2); for (String name : names2) { System.out.println(name); } When I ran it once:and again:and again: EmmaDaveCindy DaveCindyAmy AmyEmmaEmma CindyAmyDave
Returning to the boolean operators &&“and” ||“or” !“not”
(x && y) is true only if x is true and y is true truth tables –both convey same information, but in different ways &&truefalse true false xyx && y true false truefalse
(x || y) is true only if x is true or y is true truth tables –both convey same information, but in different ways ||truefalse true falsetruefalse xyx || y true false true falsetrue false
!x is true only if x is false truth tables –both convey same information, but in different ways !truefalse true x!x truefalse true
Short circuiting && and || are so-called "short circuit" operators They only evaluate as much as is needed –In an expression such as x&&y, if x is false there is no need to evaluate y (since x&&y must be false ) –In an expression such as x||y, if x is true there is no need to evaluate y (since x||y must be true )
Use of short-circuiting short-circuiting can be used to effect a form on conditional evaluation: public void shortCircuitTest(int x) { int y=5; int z=2; if ( x!=0 && (y/x)<z ) { System.out.println("Division was safe"); } else { System.out.println("Avoided divide-by-zero"); } shortCircuitTest(3) prints Division was safe shortCircuitTest(0) prints Avoided divide-by-zero