在下面的代码中,对象someObj具有两个属性,float xint pnt. 创建ArrayList<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());
    }
}

推荐答案

nextFloat()将生成范围为[0,1)的float,通过在比较器中减go 任何两个这样的值,您将得到范围(-1,1)中的值.当您将其强制转换为int时,您将得到0,这意味着根据这个比较器,它们都是相等的,并且列表将保持其顺序.

您可以通过不用-实现比较器来解决这个问题,而是通过重用Floatcompare方法来解决:

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

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

Collections.sort(oList, Comparator.comparing(someObj::getX));

EDIT:
As Andy Turner noted in the comments, Collections.sort is a bit outdated. Since JDK 8, lists have their own sort method you can invoke directly:

oList.sort(Comparator.comparing(someObj::getX));

Java相关问答推荐

如何判断一个矩阵是否为有框矩阵?

为什么JAVA&S清洁器使用链表而不是并发HashSet?

如何创建一个2d自上而下的移动系统,其中移动,同时持有两个关键是可能的处理?

如何在ApachePOI中将图像添加到工作表的页眉?

为什么S的文档中说常量方法句柄不能在类的常量池中表示?

Mac上的全屏截图在使用JavaFX时不能正常工作吗?

使用OAuth 2.0资源服务器JWT时的授权(授权)问题

%This内置函数示例

我怎样才能让IntelliJ标记toString()的任何实现?

将关闭拍卖的TimerService

AbstractList保证溢出到其他方法

如何生成指定范围内的11位序列号?

如何处理两个几乎相同的XSD文件?

有没有办法知道在合并中执行了什么操作?

在Eclipse中可以使用外部字体吗?

双对象供应商

声纳覆盖范围为 0%,未生成 jacoco.xml

如何在JavaFx中使表格的水平、垂直角的滚轮背景 colored颜色 透明?

降低无向图的时间复杂度

Spring Boot不创建数据库表