无法更改变量名称的值?

时间:2016-01-16 16:24:19

标签: java android json

我可以更改比较方法中的值吗?错误 - 变量需要声明为final,但最终不允许我更改。 我想比较一些其他变量JSONarray(如total_transit_time,total_walking_time)。我想不出另一个解决办法。有人可以教我一个更简单的方法吗?

public  JSONArray findShortest(JSONObject json_object) throws JSONException {
    JSONArray sortedJsonArray = new JSONArray();
    List<JSONObject> jsonList = new ArrayList<JSONObject>();
    for (int i = 0; i < json_object.length(); i++) {
        int name = i;
        JSONObject json_array = json_object.optJSONObject(""+name);
        jsonList.add(json_array);
    }
    System.out.println("jsonList = " + jsonList.toString());

    Collections.sort(jsonList, new Comparator<JSONObject>() {

        public int compare(JSONObject a, JSONObject b) {
            String valA = new String();
            String valB = new String();

            try {
                valA = String.valueOf(a.get("total_duration"));
                valB = String.valueOf(b.get("total_duration"));
            } catch (JSONException e) {
                //do something
            }

            return valA.compareTo(valB);
        }
    });

到这个

public  JSONArray findShortest(JSONObject json_object, String sortByThisElement) throws JSONException {
    ......

            ......

            try {
                valA = String.valueOf(a.get(sortByThisElement));
                valB = String.valueOf(b.get(sortByThisElement));
            } catch (JSONException e) {
                //do something
            }
            ......
        }
    });

1 个答案:

答案 0 :(得分:0)

您可以宣布您的sortByThisElement为最终版,然后您可以直接使用它:

public  JSONArray findShortest(JSONObject json_object, final String sortByThisElement) throws JSONException {
......

        ......

        try {
            valA = String.valueOf(a.get(sortByThisElement));
            valB = String.valueOf(b.get(sortByThisElement));
        } catch (JSONException e) {
            //do something
        }
        ......
    }
});

另一种方法是,在方法中创建一个final变量,然后在compare方法中访问它:

public  JSONArray findShortest(JSONObject json_object, String sortByThisElement) throws JSONException {
......

        ......
        System.out.println("jsonList = " + jsonList.toString());
        final String sortByThis = sortByThisElement;//note this should be add before Collections.sort 
        ........
        try {
            valA = String.valueOf(a.get(sortByThis));
            valB = String.valueOf(b.get(sortByThis));
        } catch (JSONException e) {
            //do something
        }
        ......
    }
});