1

我正在从事一个项目,在该项目中,我在初始化具有特定大小的一种方法时遇到了 TypeSafety 问题。在我的运行方法中,我有黄线new ArrayList[tableLists.size()]并抱怨 -

Type safety: The expression of type ArrayList[] needs unchecked conversion to conform to ArrayList<Method>[]

下面是代码。

private ArrayList<Method> methods[] = null;


    @Override
    public void run() {

        methods = new ArrayList[tableLists.size()];


    }

我怎样才能TypeSafety在这里解决这个问题?

更新:-

    int j = 0;
    dbConnection = new Connection[tableLists.size()];
    callableStatement = new CallableStatement[tableLists.size()];
    methods = new ArrayList[tableLists.size()];

    //loop around the map values and make the connection list
    for (Map<String, String> map : tableLists.values()) {

        dbConnection[j] = getDBConnection(map.get("URL"), map.get("USER"), map.get("PASSWORD"), map.get("DRIVER"));
        callableStatement[j] = dbConnection[j].prepareCall(map.get("SQL"));

        methods[j] = getRequiredMethods(map.get("SUFFIX"));
        j++;
    }
4

1 回答 1

3

由于这些方法本身似乎没有以任何特定方式分开,为什么不将它们全部存储在同一个ArrayList中,完全绕过问题呢?

ArrayList<Method> methods;

/* ... */

methods.addAll(getRequiredMethods(map.get("SUFFIX")));

数组和泛型往往不能很好地相互配合。如果你真的需要分离,你必须主要选择:

  1. Use an ArrayList<ArrayList<Method>> instead of an array. This will let you handle everything nicely without mucking with plain arrays. You can then efficiently initialize the methods object with a size just like with a regular array.

    methods = new ArrayList<ArrayList<Method>>(tableLists.size());
    
  2. If you really need to use an array, you'll probably have to suppress the warning using the @SuppressWarnings("unchecked") annotation. This is ugly and annoying, so I'd avoid it if you can.
于 2013-02-13T06:18:41.297 回答