简体   繁体   English

使用与数组相同的算法对ArrayList进行排序

[英]Sorting ArrayList With same Algo as Array

I am trying to sort an ArrayList by implementing a similar algorithm I have used to sort arrays. 我正在尝试通过实现用于排序数组的类似算法来对ArrayList进行排序。 I know I can use Collects.sort but as I am still a beginner I would rather write the code and learn it. 我知道我可以使用Collects.sort,但由于我仍然是初学者,所以我希望编写代码并学习它。 compare the value of two integer objects stored in an array list. 比较存储在数组列表中的两个整数对象的值。 This is my code with the scores array being passed as an argument via reference to this method. 这是我的代码,其中scores数组通过对此方法的引用作为参数传递。 Right now this code is not sorting properly but rather inserting the lowest number in the array at all subscripts. 目前,此代码未正确排序,而是在所有下标的数组中插入最低的数字。 On a side note I was curious how I could compare the scores at index j and index smallest with the compareTo() method as I am comparing objects not primitives I feel it would be a better solution than casting. 顺便说一句,我很好奇我如何用compareTo()方法比较索引j和最小索引处的分数,因为我比较的对象不是基本类型,我觉得这比强制转换更好。 Thank you! 谢谢!

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

    }

Right now this code is not sorting properly but rather inserting the lowest number in the array at all subscripts. 目前,此代码未正确排序,而是在所有下标的数组中插入最低的数字。

You need to use set() method instead of add() to replace the elements. 您需要使用set()方法而不是add()来替换元素。

On a side note I was curious how I could compare the scores at index j and index smallest with the compareTo() method as I am comparing objects not primitives I feel it would be a better solution than casting 顺便说一句,我很好奇我如何用compareTo()方法比较索引j和最小索引处的分数,因为我比较的不是原始对象,我觉得这比强制转换更好

You can avoid casting easily by specifying explit type for your collection, like new ArrayList<Integer> . 您可以通过为集合指定展开类型来避免转换,例如new ArrayList<Integer>

Gathering all together here's the corrected code: 聚集在一起的是更正后的代码:

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM