Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用与数组相同的算法排序ArrayList_Java_Sorting_Arraylist - Fatal编程技术网

Java 使用与数组相同的算法排序ArrayList

Java 使用与数组相同的算法排序ArrayList,java,sorting,arraylist,Java,Sorting,Arraylist,我正试图通过实现一个类似的算法来对ArrayList进行排序,我曾经使用该算法对数组进行排序。我知道我可以使用Collects.sort,但由于我还是一个初学者,我宁愿编写代码并学习它。比较存储在数组列表中的两个整数对象的值。这是我的代码,其中scores数组通过引用此方法作为参数传递。现在,这段代码没有正确排序,而是在数组中的所有下标处插入了最小的数字。另一方面,我很好奇如何用compareTo()方法比较索引j和最小索引的分数,因为我比较的是对象而不是原语,我觉得这是一个比铸造更好的解决方案

我正试图通过实现一个类似的算法来对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);

    }
int最小;
对于(int i=0;i<5;i++)
{
最小=i;
对于(int j=i;j
现在,这段代码没有正确排序,而是在数组中的所有下标处插入了最小的数字

您需要使用
set()
方法而不是
add()
来替换元素

在一个侧面,我很好奇,我如何能够比较索引j和index minimum的分数和compareTo()方法,因为我比较的对象不是原语,我觉得这比投射更好

通过为集合指定explit类型,如
newarraylist
,可以轻松避免强制转换

下面是正确的代码:

    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);
ArrayList分数=新建ArrayList();
分数。增加(5);
分数。增加(4);
分数。增加(2);
分数。增加(1);
分数。增加(3);
系统输出打印项次(分数);
int最小;
对于(int i=0;i
使用集合界面对列表进行排序。谢谢!非常感谢。