Java Swing (Professional web hosting) - O Reilly // Add a 2nd
Java Swing - O Reilly // Add a 2nd attribute to both sets AttributeSet oneB = con.addAttribute(oneA, StyleConstants.Foreground, Color.blue); System.out.println(”Refs are same after adding a 2nd attribute ” + “to one set? ” + (oneB == twoA)); // prints false (of course) AttributeSet twoB = con.addAttribute(twoA, StyleConstants.Foreground, Color.blue); System.out.println(”Refs are same after adding ” + “2nd attribute to 2nd set? ” + (oneB == twoB)); // prints true // remove the second attribute so it matches the old set . . . AttributeSet oneC = con.removeAttribute(oneB, StyleConstants.Foreground); System.out.println(”Old set matches new set after removal? ” + (oneC == oneA)); // prints true // show that a threshold for reusing sets is reached . . . AttributeSet tooBig1 = new SimpleAttributeSet(); AttributeSet tooBig2 = new SimpleAttributeSet(); for (int i=0; i<10; i++) { tooBig1 = con.addAttribute(tooBig1, Integer.toString(i), new Integer(i)); tooBig2 = con.addAttribute(tooBig2, Integer.toString(i), new Integer(i)); System.out.print(tooBig1 == tooBig2); System.out.print(" "); } System.out.println(); System.exit(0); } } When executed, this program produces the following output: Refs are initially to the same object? falseRefs are same after setting the same value? trueRefs are same after adding a 2nd attribute to one set? falseRefs are same after adding 2nd attribute to 2nd set? trueOld set matches new set after removal? true true true true true true true true true true false Initially, we created two new sets and checked to see if they referred to the same object. Since both were created using new(), this of course returns false. Next, we add the same attribute (bold=true) to each set and compare the sets returned from the two addAttribute() calls. The StyleContext has returned the same instance in both cases, so a comparison of oneA and twoA returns true. We then add a second attribute (foreground=blue) to the first set. The returned value (oneB) is, as you'd expect, not the same as twoA. However, adding the second attribute to the second set as well results in another shared set. We then remove this attribute from the first set and confirm that the returned set is the same set we had before adding the second attribute. Finally, we show that this set reuse is only done on small sets. In this last portion of the example, we add some toy attributes to two sets and show that the sets returned by addAttribute() match until we exceed the threshold, when we get separate set objects, even though they still contain the same key/value pairs. 21.1.5.6 A Look Inside - 708
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.