繁体   English   中英

我不知道比较器

[英]I can't figure out comparator

我正在尝试对一个数组列表进行排序,但是我无法将头包裹在比较器上。 我不明白如何从由文本文件创建的数组列表中定义可排序字段。 此外,我不确定比较器逻辑。 在我看来,似乎要创建一组比较器函数,然后再调用它们。 这是真的?

到目前为止,我的代码如下所示:

public class coord implements Comparator<Sort> {
    private int index;
    private int index2;
    private double dista;
}

public class Sort {
List<Sort> coords = new ArrayList<Sort>();


public static void main(String[] args) throws Exception {
    ArrayList dist = new ArrayList();
    File file = new File("2.txt");
    FileWriter writer = new FileWriter("2c.txt");
    try {
        Scanner scanner = new Scanner(file).useDelimiter("\\s+");

        while (scanner.hasNextLine())
        {
            int index = scanner.nextInt();
            int index2 = scanner.nextInt();
            double dista = scanner.nextDouble();
            System.out.println(index + " " + index2 + " " + dista);
        }
    }
}
        public class EmpSort {
            static final Comparator<coord> SENIORITY_ORDER =
                                         new Comparator<coord>() {
                public int compare(coord e1, coord e2) {
                    return e2.index().compareTo(e1.index());
                }
            };
            static final Collection<coord> coords = ;

            public static void main(String[] args) {
                List<Sorted>e = new ArrayList<Sorted>(coords);
                Collections.sort(e, SENIORITY_ORDER);
                System.out.println(e);

感谢任何人可以提供的帮助。

比较器逻辑很简单。 对元素数组进行排序时,有两种选择-在每个元素上使用Comparable进行排序(假设有一个元素)或提供一个Comparator。 如果您的数组包含复杂的元素或有不同的排序标准,则后一种选择可能是您需要使用的选择。

每次调用比较器时,您都必须说元素1“小于”元素2在这种情况下返回负数,元素1是“大于”元素3在这种情况下返回正数。 否则,如果元素相等,则返回0。您还可以在比较值之前进行引用和null比较,以使null元素在逻辑上“小于”非null元素,依此类推。

如果元素是“相等的”,那么您可能希望先按次要字段排序,然后再按第三个字段排序,直到排序顺序明确为止。

一个复杂类的简单比较器,它具有字段a和b,我们要对a进行排序:

class Complex {
  public String a = "";
  public String b = "";
}

//...

Collections.sort(someList, new Comparator<Complex>() {
  public int compare(Complex e1, Complex e2) {
    if (e1 == e2) {
      // Refs could be null or equal
      return 0;
    }
    if (e1 == null && e2 != null) {
      return -1;
    }
    if (e2 == null && e1 != null) {
      return 1;
    }
    if (e1.a == e2.a) {
      return 0;
    }
    if (e1.a == null && e2.a != null) {
      return -1;
    }
    if (e1.a != null && e2.a == null) {
      return 1;
    }
    // Just use the Comparable on the fields
    return e1.a.compareTo(e2.a);
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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