Java Reference
In-Depth Information
By design, the quality table should only hold floating-point values (as Float objects).
However, the class compiles successfully regardless of the class of the value added to a
table. You might goof and unintentionally add a string to the table, as in this revised
statement:
8
quality.put(“near mint”, “1.50”);
The class compiles successfully, but when it is run, it stops with a ClassCastException
error in the following statement:
comix[1].setPrice( (Float) quality.get(comix[1].condition) );
The reason for the error is that the statement tries to cast the table's “near mint” value to
a Float , which fails because it receives the string “1.50” instead.
For obvious reasons, runtime errors are much more troublesome for programmers than
compiler errors. A compiler error stops you in your tracks and must be fixed before you
can continue. A runtime error might creep its way into the code, unbeknownst to you,
and cause problems for users of your software.
The class or classes expected in a data structure can be specified using a feature of the
language called generics.
The expected class information is added to statements where the structure is assigned a
variable or created with a constructor. The class or classes are placed within “<” and “>”
characters and follow the name of the class, as in this statement:
Vector<Integer> zipCodes = new Vector<Integer>;
This statement creates a Vector that will be used to hold Integer objects. Because the
vector is declared in this manner, the following statements cause a compiler error:
zipCodes.add(“90210”);
zipCodes.add(“02134”);
zipCodes.add(“20500”);
The compiler recognizes that String objects do not belong in this vector. The proper
way to add elements to the vector is to use integer values:
zipCodes.add(90210);
zipCodes.add(02134);
zipCodes.add(20500);
Data structures that use multiple classes, such as hash tables, take these class names sep-
arated by commas within the “<” and “>” characters.
Search WWH ::




Custom Search