【问题标题】:I want to create an ArrayList with a dynamic index not starting from 0我想创建一个动态索引不是从 0 开始的 ArrayList
【发布时间】:2020-05-18 02:52:45
【问题描述】:
 public void jsonParse(){
    jsonResArray = new ArrayList< >();
    String url = "my-api-url";
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new 
        Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray jsonArray = response.getJSONArray("data");
                if(jsonArray.length()!=0) {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        int id =Integer.parseInt(jsonObject.getString("service_id"));
                        **jsonResArray.add(id, jsonObject.getString("service_name"));**
                        }}
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getBaseContext() , e.toString() , Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getBaseContext(),error.getMessage(),Toast.LENGTH_SHORT).show();
        }
    });
    mQueue.add(request);
}

我想创建动态索引,因为我想将服务名称与其 id 保存在字符串数组中,但它给了我 bp 之外的索引 提前致谢

【问题讨论】:

    标签: java android arraylist indexing dynamic


    【解决方案1】:

    使用Map&lt;Integer, String&gt; 而不是ArrayList&lt;String&gt;

    【讨论】:

      猜你喜欢
      • 2011-02-17
      • 2017-12-10
      • 1970-01-01
      • 2017-06-08
      • 2015-11-21
      • 1970-01-01
      • 2023-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多