1

The sort method Collections.sort(list) works on the list even though I pass by reference. However, when I use the following method, the list does not get sorted.

public void getSortedList(ArrayList<String> currList) {
    ArrayList<String> list = new ArrayList<>();

    Cursor cursor = database.rawQuery(
            "SELECT * FROM " + TABLE_NAME + " ORDER BY name DESC", null);

    while (cursor.moveToNext()) {
        String name = cursor.getString(0);
        if (currList.contains(name)) {
            list.add(name);
        }
    }
    cursor.close();

    currList = list;
}
geft
  • 615
  • 1
  • 6
  • 18

1 Answers1

0

currList = list; doesn't change the reference that you passed to the method, since Java is a pass by value language.

Instead, you should return the list :

public List<String> getSortedList()
{
    List<String> list = new ArrayList<>();
    ...
    return list;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • The OP wants to sort a list passed as a parameter. He doesn't want to create the list in the sort method and sort it. – Chetan Kinger Mar 05 '15 at 14:49
  • Why does `Collections.sort(list)` work then? – geft Mar 05 '15 at 14:51
  • @bot Based on the OP's code, that's not what they are trying to do. The list is created inside the method (and sorted by the SQL statement). The parameter that was passed to the method was a (wrong) attempt to change the list reference passed to the method. – Eran Mar 05 '15 at 14:51
  • 1
    @geft Collections.sort(list) doesn't create a new list and try to assign it to the passes list reference. It mutates the instance referred by the passed reference. – Eran Mar 05 '15 at 14:52
  • @Eran. You are right. My bad. – Chetan Kinger Mar 05 '15 at 14:54