按引用对列表进行排序

时间:2015-03-05 14:43:02

标签: java reference

即使我通过引用传递,排序方法Collections.sort(list)仍在列表中工作。但是,当我使用以下方法时,列表不会被排序。

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

1 个答案:

答案 0 :(得分:0)

currList = list;不会更改传递给方法的引用,因为Java是一种按值传递的语言。

相反,您应该返回列表:

public List<String> getSortedList()
{
    List<String> list = new ArrayList<>();
    ...
    return list;
}