[英]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.