0

Can i change the value inside the compare method? Error - variable need to be declared final, but final wont allow me to change. I want to compare some other variables the JSONarray(like total_transit_time, total_walking_time). i cant think of another solution to do that. could someone teach me an easier way to do it?

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);
        }
    });

to this

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
            }
            ......
        }
    });
h p2ter
  • 25
  • 5

1 Answers1

0

You can declare your sortByThisElement to be final,then you can use it directly:

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
        }
        ......
    }
});

the other way is,create a final variable in your method,then visit it in your compare method:

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
        }
        ......
    }
});
starkshang
  • 8,228
  • 6
  • 41
  • 52