Java 未经检查地调用 add(E) 作为原始类型 ArrayList 和 HashMap 的成员

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24548656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:53:09  来源:igfitidea点击:

unchecked call to add(E) as a member of the raw type ArrayList and HashMap

java

提问by ant2009

I have the following function that uses org.json.simple to create JSON object.

我有以下使用 org.json.simple 创建 JSON 对象的函数。

public JSONObject createJSONRequest() {
    // /* Create JSON Objects */
    JSONObject jsonObject = new JSONObject();
    Map<String, String> map = new HashMap<String, String>();

    map.put(ACCESS_TOKEN_KEY, mAccessToken);            
    map.put(SESSION_ID_KEY, mSessionId);
    map.put(SNAPZ_ID_KEY, mSnapzId);
    map.put(EMAIL_KEY, mEmail);
    map.put(EMAIL_PWD_KEY, mEmailPwd);

    JSONArray list = new JSONArray();
    list.add(map);
    jsonObject.put("parameters", list);
    jsonObject.put("function", "verifyEmail");

    return jsonObject;
}

However, I keep getting this warning when I use lint checker.

但是,当我使用 lint 检查器时,我不断收到此警告。

[unchecked] unchecked call to add(E) as a member of the raw type ArrayList
        list.add(map);
                ^
where E is a type-variable: E extends Object declared in class ArrayList

 warning: [unchecked] unchecked call to put(K,V) as a member of the raw type HashMap
        jsonObject.put("parameters", list);
                      ^
where K,V are type-variables:
    K extends Object declared in class HashMap
    V extends Object declared in class HashMap

warning: [unchecked] unchecked call to put(K,V) as a member of the raw type HashMap
        jsonObject.put("function", "verifyEmail");

I have tried to use the generic type. HashMap uses generics, but the other objects JSONObjectJSONArraydon't.

我尝试使用泛型类型。HashMap 使用泛型,但其他对象JSONObjectJSONArray不使用。

Many thanks for any suggestions,

非常感谢您的任何建议,

采纳答案by bitkot

You are getting this warning because the library uses raw type collections internally. To hide this warning you annotate your method with @SuppressWarnings("unchecked").

您收到此警告是因为库在内部使用原始类型集合。要隐藏此警告,请使用@SuppressWarnings("unchecked").

If you want to use json library with generics support. You can go for Google GSOn. I have used it myself in many projects. It is easy and uses generic collections.

如果您想使用具有泛型支持的 json 库。你可以去谷歌 GSOn。我自己在很多项目中都使用过它。它很容易并且使用泛型集合。