尝试使用比较器对 ArrayList 进行排序

4ul*_*lls 2 java sorting arraylist comparator

在下面的代码中,该对象someObj有两个属性: afloat x和 an int pnt。AnArrayList<someObj>被创建,然后Comparator根据 x 使用接口进行排序。该属性pnt旨在跟踪排序后的元素。

我从https://www.geeksforgeeks.org/collections-sort-java-examples/复制了代码 ,并对其进行了一些修改以满足我的需求。我想知道可能出了什么问题,它只是没有完成排序工作。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;

public class ArrayListSorting {

   public static void main(String[] args) {
       
       // 20 random numbers will be used for the test
       final int sz=20;
       Random rand = new Random();
       
       ArrayList<someObj> oList=new ArrayList<someObj>();
      
      // Build the list
      for(int i=0;i<sz;i++) {
          oList.add(new someObj(i,rand.nextFloat()));
      }
    
      // Print the list before sorting
      for(int i=0;i<sz;i++) {
          System.out.println(i+"\t"+oList.get(i).getX());
      }

      Collections.sort(oList, new sorter());

      // ...and after sorting
      for(int i=0;i<sz;i++) {
          int j=oList.get(i).getPnt();
          System.out.println(j+"\t"+oList.get(i).getX());
      }

   }
}

class someObj {

    private float x;
    private int pnt;
    
    public someObj(int pnt,float x) {
        this.pnt=pnt;
        this.x=x;
    }
    
    public int getPnt() {
        return pnt;
    }
    
    public float getX() {
        return x;
    }
}

class sorter implements Comparator<someObj> {
    
    public int compare(someObj a, someObj b) {
        return (int)(a.getX() - b.getX());
    }
}
Run Code Online (Sandbox Code Playgroud)

Mur*_*nik 8

nextFloat()将生成float[0,1) 范围内的 a,通过在比较器中减去任意两个这样的值,您将得到 (-1, 1) 范围内的值。当您将其转换为 an 时,int您将得到 0,这意味着根据此比较器,它们都是等效的,并且列表将保留其顺序。

您可以通过不使用 实现比较器-,而是通过重用 的Float方法来解决此问题compare

class sorter implements Comparator<someObj> {
    
    public int compare(someObj a, someObj b) {
        return Float.compare(a.getX(), b.getX());
    }
}
Run Code Online (Sandbox Code Playgroud)

或者更好的是,使用Comparator.comparing动态创建此比较器:

Collections.sort(oList, Comparator.comparing(someObj::getX));
Run Code Online (Sandbox Code Playgroud)

编辑:
正如安迪·特纳在评论中指出的那样,Collections.sort有点过时了。从 JDK 8 开始,列表有自己的sort方法,您可以直接调用:

oList.sort(Comparator.comparing(someObj::getX));
Run Code Online (Sandbox Code Playgroud)