Java Reference
In-Depth Information
}
public static void main(String[] args) {
Pair p = new Pair<Object>(23, "skidoo");
System.out.println(p.first() + " " + p.second());
for (String s : p.stringList())
System.out.print(s + " ");
}
}
Solution 88: Raw Deal
This program appears reasonably straightforward. It creates a pair whose first element is the
Integer
representing 23 and whose second element is the string
"skidoo"
. Then the program prints
the first and second elements of the pair, separated by a space. Finally, it iterates over the string
representations of these elements and prints them again, so it ought to print
23 skidoo
twice. Sadly,
it doesn't even compile. Worse, the compiler's error message is terribly confusing:
Pair.java:26: incompatible types;
found: Object, required: String
for (String s : p.stringList())
^
This message would make sense if
Pair.stringList
were declared to return
List<Object>
, but it
returns
List<String>
. What on earth is going on?
This rather surprising behavior is caused by the program's use of
raw
types. A raw type is simply the
name of a generic class or interface without any type parameters. For example,
List<E>
is a generic
interface,
List<String>
is a parameterized type, and
List
is a raw type. In our program, the sole
use of raw types is the declaration of the local variable
p
in
main
:
Pair
p = new Pair<Object>(23, "skidoo");
Search WWH ::
Custom Search