Download presentation
Presentation is loading. Please wait.
1
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?
2
Collections interface: java.util.Collection classes: –java.util.HashSet –java.util.ArrayList E is the type of element contained in the collection
3
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”); …
4
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
5
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.
6
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”); …
7
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
8
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
9
Returning to the boolean operators &&“and” ||“or” !“not”
10
(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
11
(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
12
!x is true only if x is false truth tables –both convey same information, but in different ways !truefalse true x!x truefalse true
13
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 )
14
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.