Generics problem

Even more blind than my usual self...

public void test() {
     List<?> s = new ArrayList<String>();
     List<List<String>> data = new ArrayList<List<String>>();
     List<List<?>> x = data;
     List<List<?>> y = (List<List<?>>) data;
     List<List<?>> z = new ArrayList<List<?>>(data);
}

In my (it seems dumb) opininon, "List<List<?>> x = data;" should be legal.

Idea marks "List<List<?>> x = data;" as an error, and "List<List<?>> y = (List<List<?>>) data;" as an unchecked cast.

javac (1.6.0_24) refuses to compile both lines.

As an workaround, "List<List<?>> z = new ArrayList<List<?>>(data);" passes muster and that's what I'm using for now.

Who's right and who's wrong? Should I create a bug entry because idea doesn't mark the cast as an error?

Help a poor blind programmer please :)

0
2 comments

This works:

    public void test() {
        List<?> s = new ArrayList<String>();
        List<List<String>> data = new ArrayList<List<String>>();
        List<? extends List<?>> x = data;
    }


I learnt to not fight against java generics, thus I can't say for sure why you need an extra wildcard (I don't see any need myself), but it seems to make java compiler happy.

0

Tank you very much.

I had completely forgotten aobut the extends option and it works for this case (I'm now fighting another where the extends isn't working ?:| .)


Note: created IDEA-66750 issue for idea not flagging the invalid cast as an error.

0

Please sign in to leave a comment.