Arne Vajhøj said:
Java and C# has almost the same syntax for generics, but
the implementation in Java byte code and MSIL is very
different.
Well, they have similar syntax for a small part of it - the way a
generic type name is written, eg List<String>. They differ in:
o How constraints are expressed
o How generic methods are declared
o Covarance/contravariance
Java generics basically disappear in the Java byte code. In
most cases it is not significant. But in some cases it
can cause unexpected results for the programmer who have
not understood the concept.
Unfortunately it makes things very limiting in some ways, because the
information isn't available at runtime. It becomes unsafe (in unobvious
ways) to cast to a generic type, whereas in .NET the cast can be
checked properly at runtime.
Of course, Java has covariance and contravariance which C# doesn't
support, so it's not all one-way...
I can not see any connection between type erasure and
boxing/unboxing.
ArrayList<int> is not valid in Java. Accessing an
ArrayList<Integer> does not cause any boxing/unboxing.
Boxing/unboxing between Integer and int obviously
causes boxing/unboxing.
It's worth remembering that another feature of Java 5 is auto-boxing
and auto-unboxing though, so if you do:
List<Integer> list = new ArrayList<Integer>();
list.add(5);
int x = list.get(0);
that's okay.
What's slightly surprising is that boxing doesn't always create a new
object:
Integer a1 = 5;
Integer a2 = 5; // Now a1==a2
but
Integer a3 = 4000;
Integer a4 = 4000; // a3!=a4
(Obviously a3.equals(a4), but the references aren't equal.)
Just a little bit of trivia...