Java Reference
In-Depth Information
The dilemma with the ComicBook application can be remedied by changing line 10 to the
following:
Hashtable<String, Float> quality = new Hashtable<String, Float>();
This sets up a table to use String objects for keys and Float objects for values. With
this statement in place, a string can no longer be added as the value for a condition such
as “near mint.” A compiler error flags a problem of this kind.
Generics also make it simpler to retrieve an object from a data structure—you don't have
to use casting to convert them to the desired class. For example, the quality table no
longer requires a cast to produce Float objects in statements like this one:
comix[1].setPrice(quality.get(comix[1].condition));
From a stylistic standpoint, the addition of generics in variable declarations and construc-
tor methods is likely to appear intimidating. However, after you become accustomed to
working with them (and using autoboxing, unboxing, and the new for loops), data struc-
tures are significantly easier to work with and less error-prone.
The CodeKeeper2 class in Listing 8.4 is rewritten to use both generics and the new for
loop that can iterate through data structures like vectors.
LISTING 8.4
The full text of CodeKeeper2.java
1: import java.util.*;
2:
3: public class CodeKeeper2 {
4: Vector<String> list;
5: String[] codes = { “alpha”, “lambda”, “gamma”, “delta”, “zeta” };
6:
7: public CodeKeeper2(String[] userCodes) {
8: list = new Vector<String>();
9: // load built-in codes
10: for (int i = 0; i < codes.length; i++) {
11: addCode(codes[i]);
12: }
13: // load user codes
14: for (int j = 0; j < userCodes.length; j++) {
15: addCode(userCodes[j]);
16: }
17: // display all codes
18: for (String code : list) {
19: System.out.println(code);
20: }
21: }
22:
23: private void addCode(String code) {
Search WWH ::




Custom Search