I know from https://stackoverflow.com/a/20445493/2848676 that the following code gives the error type mismatch cannot convert from element type object to string
:
ArrayList objectArray = new ArrayList();
for (String str : objectArray) {
The compiler is giving me a warning in my declaration of objectArray that says ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized
. This all makes perfect sense to me. The fix is to specify the generic types:
ArrayList<String> stringArray = new ArrayList<String>();
for (String str : stringArray) {
This avoids the compiler warning and the compilation error.
My problem though is I'm trying to iterate over a subclass of ArrayList called org.json.simple.JSONArray
and I don't have control over how the JSONArray is instantiated. Consequently I don't see the compiler warning anywhere but I do get the compilation error in this for
loop line of code:
JSONArray insights = (JSONArray)jsonResult.get("insights");
for (JSONObject insightGroup : insights) {
I know I can work around this like this:
JSONArray insights = (JSONArray)jsonResult.get("insights");
for (int i=0; i<insights.size(); i++) {
JSONObject insightGroup = (JSONObject) insights.get(i);
But can someone explain the finer points of generic types? In particular, how can the org.json.simple.JSONArray
be instantiated without specifying the generic types? Is org.json.simple.JSONArray
just poorly designed? Or am I not using the org.json.simple.JSONArray
correctly?