次の方法で共有


SF/JavaOne, Day 3, JavaGenericsWhaaaa?!

I'm at the Java Collections talk and they're bringing up the issue of
type safety with generics in java 1.5.  The speaker just told me
somethign that sent a shiver up my spine.  Let's say you compiled
the following code in java1.4:

class Old {

    static void addIntegerToList(List list) {

        list.Add(new Integer(42));

    }

}

then in java1.5 you write and compile the following code:

class New {

    static void Foo() {

        List<String> strings = new ArrayList<String>();

        Old.addIntegerToList(strings);

        Srting firstString = strings.getAt(0);

    }

}

Then the above code compiles fine without a single warning!  Ack!

Double-ack!

Ack*Ack*Ack!

The compiler will make you think that everything is typesafe and you
won't know that anything is wrong with your type system until it blows
up at runtime.

Comments

  • Anonymous
    June 28, 2005
    So does this apply to .NET 2, too?
  • Anonymous
    June 28, 2005
    Uwe: No, it does not. C# will not let this compile at all. This is a consequence of the fact that in java generics are forgotten (or "erased") so the compiler can't tell if your original code was:

    class Old {
    ....static void addIntegerToList(List list) {
    ........//stuff
    ....}
    }

    or if it was

    class Old {
    ....static void addIntegerToList(List<String> list) {
    ........//stuff
    ....}
    }

    the compiled form for both is identical. So it can only presume that things were performed in a typesafe manner. Which, of course, might be totally wrong.

    In C#/.Net this generic information is not lost. It is preserved in metadata so you can't ever have this kind of problem occurring.
  • Anonymous
    June 28, 2005
    Uh, duh. This is why I've pointed out in numerous places that Java doesn't have real generics....
  • Anonymous
    June 29, 2005
    The comment has been removed
  • Anonymous
    June 30, 2005
    The comment has been removed
  • Anonymous
    July 01, 2005
    The comment has been removed
  • Anonymous
    October 13, 2005
    The comment has been removed