在Android中排序ArrayLists

我正在开发一个应用程序。我想排序ArrayList。我面临的问题是,每当我有一个重复的条目,排序失败,应用程序崩溃。在Android中排序ArrayLists

布局截至目前是:

而我希望有结果以下列方式:

我写下面一段代码分类。

private void sortAlphaNumeric() { 

/* Take a temporary list to store the original list */

/*

* Remove any white spaces in the question number as it might

* interfere in sorting

*/

String[] trimmedArray = new String[m_quesNumber.size()];

for (int i = 0; i < m_quesNumber.size(); i++) {

trimmedArray[i] = m_quesNumber.get(i).replace(" ", "");

}

m_quesNumber = new ArrayList<String>();

for (int i = 0; i < trimmedArray.length; i++) {

m_quesNumber.add(trimmedArray[i]);

}

ArrayList<String> temp_quesNumber = new ArrayList<String>(

m_quesNumber);

/* Sort the original list */

Collections.sort(m_quesNumber, new AlphanumComparator());

/* Temporary arrays */

String[] temp_prevQuesId = new String[m_quesId.size()];

String[] temp_quesMaxMarks = new String[m_quesMaxScore.size()];

Integer[] temp_quesOptional = new Integer[m_quesOptional.size()];

for (int i = 0; i < m_quesNumber.size(); i++) {

int old_position = temp_quesNumber.indexOf(m_quesNumber.get(i));

temp_prevQuesId[i] = m_quesId.get(old_position);

temp_quesMaxMarks[i] = m_quesMaxScore.get(old_position);

temp_quesOptional[i] = m_quesOptional.get(old_position);

}

m_quesId = new ArrayList<String>();

m_quesMaxScore = new ArrayList<String>();

m_quesOptional = new ArrayList<Integer>();

for (int i = 0; i < temp_prevQuesId.length; i++) {

m_quesId.add(temp_prevQuesId[i]);

m_quesMaxScore.add(temp_quesMaxMarks[i]);

m_quesOptional.add(temp_quesOptional[i]);

}

}

回答:

只用这个而不是所有的代码。

ArrayList<ArrayList<String>> data; //then initialize it 

// and pass it here. Sort based on column 0

Collections.sort(data, new Comparator<ArrayList<String>>() {

@Override

public int compare(ArrayList<String> row1, ArrayList<String> row2) {

return row1.get(0).compareTo(row2.get(0));

}

});

回答:

做一个模型类像...

class Result { 

String qNo;

int marksScored;

int maximumMarks;

...

}

做出的Result的ArrayList像

List<Result> results = new ArrayList<>(); 

添加所需的数据,之后您可以通过给定的代码排序。

Collections.sort(results, new Comparator<Result>() { 

@Override

public int compare(Result lhs, Result rhs) {

return lhs.qNo.compareToIgnoreCase(rhs.qNo);

}

});

以上是 在Android中排序ArrayLists 的全部内容, 来源链接: utcz.com/qa/264955.html

回到顶部