问题
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:
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 themethods
object with a size just like with a regular array.methods = new ArrayList<ArrayList<Method>>(tableLists.size());
- 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