add(new Object());
and now the equivalent nongeneric code:
ArrayList strings = new ArrayList();
strings.add("hello");
String entry = (String) strings.get(0);
strings.add(new Object());
They would generate the same Java bytecode, except for the last line??”which is valid
in the nongeneric case but caught by the compiler as an error in the generic version.
You can use a generic type as a ???raw??? type, which is equivalent to using
java.lang.Object for each of the type arguments. This rewriting??”and loss of information
??”is called type erasure. Java doesn??™t have user-defined value types, but you can??™t
even use the built-in ones as type arguments. Instead, you have to use the boxed version
??”ArrayList
for a list of integers, for example.
You may be forgiven for thinking this is all a bit disappointing compared with
generics in C#, but there are some nice features of Java generics too:
?– The runtime doesn??™t know anything about generics, so you can use code compiled
using generics on an older version, as long as you don??™t use any classes or
methods that aren??™t present on the old version. Versioning in .NET is much
stricter in general??”you have to compile using the oldest environment you want
to run on. That??™s safer, but less flexible.
?– You don??™t need to learn a new set of classes to use Java generics??”where a nongeneric
developer would use ArrayList, a generic developer just uses Array-
List.
Pages:
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237