Type safety: The expression of type ArrayList[] needs unchecked conversion

血红的双手。 提交于 2019-12-25 04:43:14

问题


I am working on a project in which I am getting TypeSafety issues on initializing one method with a particular size. In my run method, I have yellow line on the new ArrayList[tableLists.size()] and complaining about-

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

Below is the code.

private ArrayList<Method> methods[] = null;


    @Override
    public void run() {

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


    }

How can I fix this TypeSafety issue here?

Updated:-

    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++;
    }

回答1:


Since the methods themselves don't seem to be separated in any particular way, why not just store them all in the same ArrayList, bypassing the problem entirely?

ArrayList<Method> methods;

/* ... */

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

Arrays and generics tend not to play very nice with each other. If you really need the separation, you have to primary options:

  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.


来源:https://stackoverflow.com/questions/14847480/type-safety-the-expression-of-type-arraylist-needs-unchecked-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!