Java generation and array initialization

What is the explanation for the following:

public class GenericsTest { //statement 1 public ArrayList<Integer>[] lists; public GenericsTest() { //statement 2 lists = new ArrayList<Integer>[4]; } } 

The compiler accepts statement 1. Statement 2 is marked by the compiler to โ€œcreate a shared arrayโ€.

A good explanation that I saw regarding the rejection of shared arrays is this one , arguing that since arrays are covariant and generics are you cannot undermine typical typing if you have allowed shared arrays.

Leaving aside the argument about whether the language should go to the extreme stages of creating such a complex inconsistency in the treatment of generics so that you do not shoot yourself no matter how hard you try (and if anyone knows about good discussions about the relative merits / faults of the problem, please write to me, I would be interested to see the arguments), why do I need to state (1) if (2) is not?

+18
java arrays generics
Jan 22 '09 at 17:58
source share
4 answers

It seems like there are obscure cases where you can inadvertently throw a ClassCastException, as described here http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf (section 7.3)

An interesting discussion of this topic can be found here http://courses.csail.mit.edu/6.170/old-www/2006-Spring/forum/index.php%3Ftopic=324.msg1131.html

+1
Jan 22 '09 at 18:24
source share

This is because you cannot create, but you can use them:

 public class GenericsTest { //statement 1 public ArrayList<Integer>[] lists; public GenericsTest() { //statement 2 lists = new ArrayList[4]; //statement 3 lists[0].add(new Integer(0)); //statement 4 lists[0].add(new String("")); } } 

Statement 3 is possible, statement 4 will lead to a compiler error.

+6
Jan 22 '09 at 18:19
source share

So, the actual question is: why is there no error for declaring a shared array?

You will always get an error in the place where you are doing something wrong. Adding an error, when technically the problem does not arise, simply adds to the mess (although the editor may want to point this out to you).

In some cases, you may need to reduce the rules a bit with an unchecked throw. There is no need to force the code to hammer in more warning suppressions than necessary (other than stupid).

0
Jan 23 '09 at 1:04
source share

In this case, I would not use arrays precisely for this reason. Declaring "lists" in source code may be

 List<List<Integer>> lists = new ArrayList<List<Integer>>(4); for(int i = 0; i < 4; i++) lists.add(null); // or add an empty ArrayList<Integer> 

(you should use an interface, not an implementation in variable declarations)

Instead of the syntax of array [], you should use get () or set (). Other than that, it is equivalent.

-one
Jan 22 '09 at 20:59
source share



All Articles