JDK-6229728 : Allow special cases of generic array creation.
  • Type: Enhancement
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 5.0
  • Priority: P3
  • Status: Closed
  • Resolution: Won't Fix
  • OS: solaris_10
  • CPU: sparc
  • Submitted: 2005-02-16
  • Updated: 2012-01-03
  • Resolved: 2005-02-16
Description
The following does not compile, but I believe it could be made to do so.

1. Note that "lists" is a private variable.
2. Note that "lists" is not passed as an argument to any method.
3. Note that each element of "lists" is assigned using the constructor
   ArrayList<String>() which matches the type of the declaration.

Under these restrictions, I believe that generic array creation is safe.
(These restrictions would naturally be satisfied by users of my class
library.  Implementing this RFE would allow me to generify my classes
without causing customers to see unchecked warnings when creating arrays
of my classes.)


import java.util.*;

public class GenericRfe {

    private ArrayList<String>[] lists = new ArrayList<String>[2];

    public GenericRfe() {
        for (int i = 0; i < lists.length; ++i) {
            lists[i] = new ArrayList<String>();
        }
    }

    public void add(String s) {
        lists[0].add(s);
    }

    public String get(int i) {
        return lists[0].get(i);
    }

    public static void main(String[] args) {
        GenericRfe gr = new GenericRfe();
        gr.add("Testing");
        String testing = gr.get(0);
        System.out.println(testing);
    }

}

###@###.### 2005-2-16 02:39:59 GMT

Comments
EVALUATION In general it is a very limited set of programs in which it can be statically determined that arrays of generic types are used safely. In addition to the submitters constraints, other constraints must also be met: * "lists" must not be cast: ((ArrayList[])lists)[0] = new ArrayList<String>(); * elements of "lists" must not be raw: lists[0] = new ArrayList(); * "lists" must not be returned: List<String>[] getLists() { return lists; } * "lists" must not be saved in a non-private variable. * "lists" must not be accessed using reflection. There is actually no way to guard against reflective access to the lists field. ###@###.### 2005-2-16 06:14:09 GMT
16-02-2005