[英]Sorting ArrayList With same Algo as Array
我正在嘗試通過實現用於排序數組的類似算法來對ArrayList進行排序。 我知道我可以使用Collects.sort,但由於我仍然是初學者,所以我希望編寫代碼並學習它。 比較存儲在數組列表中的兩個整數對象的值。 這是我的代碼,其中scores數組通過對此方法的引用作為參數傳遞。 目前,此代碼未正確排序,而是在所有下標的數組中插入最低的數字。 順便說一句,我很好奇我如何用compareTo()方法比較索引j和最小索引處的分數,因為我比較的對象不是基本類型,我覺得這比強制轉換更好。 謝謝!
int smallest;
for (int i = 0; i < 5; i++)
{
smallest = i;
for (int j = i; j < scores.size(); j++)
{
if ((Integer) scores.get(j) < (Integer) scores.get(smallest))
smallest = j;
}
int temp = (Integer) scores.get(i);
int swap = (Integer) scores.get(smallest);
scores.add(i, swap);
scores.add(smallest, temp);
}
目前,此代碼未正確排序,而是在所有下標的數組中插入最低的數字。
您需要使用set()
方法而不是add()
來替換元素。
順便說一句,我很好奇我如何用compareTo()方法比較索引j和最小索引處的分數,因為我比較的不是原始對象,我覺得這比強制轉換更好
您可以通過為集合指定展開類型來避免轉換,例如new ArrayList<Integer>
。
聚集在一起的是更正后的代碼:
ArrayList<Integer> scores = new ArrayList<Integer>();
scores.add(5);
scores.add(4);
scores.add(2);
scores.add(1);
scores.add(3);
System.out.println(scores);
int smallest;
for (int i = 0; i < scores.size(); i++)
{
smallest = i;
for (int j = i; j < scores.size(); j++)
{
if (scores.get(j) < scores.get(smallest))
smallest = j;
}
int temp = scores.get(i);
int swap = scores.get(smallest);
scores.set(i, swap);
scores.set(smallest, temp);
}
System.out.println(scores);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.