Issue
I have some data stored in Java elements and I need to return it in a given format - JSONObject. While my implementation works fine, I'm still getting a warning message from eclipse (Version: Juno Service Release 2):
"Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap should be parameterized"
This is my code:
public interface Element {...}
public abstract class AbstractElement implements Element {...}
public final class Way extends AbstractElement {...}
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class WayToJsonConverter{
...
public JSONObject wayToJson(){
JSONObject obj = new JSONObject();
obj.put("id",way.getId());
...
return obj;
}
...
}
The problematic line is : obj.put("id",way.getId());
Is there a way to solve this issue other then adding @SuppressWarnings("unchecked")
?
Solution
What is your JSONObject, does it inherit from HashMap? If does, the warn probably means that your should declare the JSONObject instance as follows:
JSONObject<String,Object> obj=new JSONObject<String,Object>();
Updated: Look at the definition of the JSONObject:
public class JSONObject extends HashMap
it extends HashMap but doesn't support parameter type, if its definition is
public class JSONObject<K,V> extends HashMap<K,V>
then we could write
JSONObject<String,Object> obj=new JSONObject<String,Object>();
and the put method will no longer generate the warning
Answered By - ltebean