代码之家  ›  专栏  ›  技术社区  ›  APerry

选择使用对象的ArrayList排序[关闭]

  •  -4
  • APerry  · 技术社区  · 12 年前

    我在排序时遇到了一些问题。它只会按顺序正确显示第一个文件。有人看到我做错了什么吗?我已经想了好几个小时了,就是不知道自己做错了什么。

    public void sort() { 
    
        int i; //loop control
        int last; //last position in the arraylist
        int max; //position where last alphabetical filename is found
    
        max = 0; //largest position so far is first, since i haven't checked
    
        //I thought i should start at the end and work my way down
        for(last = fileList.size()-1; last >= 0; last--) {
    
            for(i = 0; i < fileList.size(); i++) {
                if(fileList.get(max).getFileName().compareTo(fileList.get(i).getFileName()) > 0)
                    max = i;
            }
    
            //swap pixfile in last position with the last alphabetical
            Pixfile tempPix = fileList.get(last);
            fileList.set(last, fileList.get(max));
            fileList.set(max, tempPix);
            //i thought i would repeat until last = 0 and the arraylist is sorted
        }//end for
    
    }
    
    1 回复  |  直到 12 年前
        1
  •  1
  •   jedyobidan    12 年前

    内部for循环应为 for(int i = 0; i <= last; i++) 因为你正在从尚未排序的东西中选择最好的。在上一次之后,您已经在外部循环的先前迭代中对所有内容进行了排序。

    此外,您没有重置的值 max 在每次迭代中,所以在内部for循环之前 max = 0;

    此外,如果你懒得编写排序算法,你可以随时使用 Arrays.sort() Collections.sort()