我无法弄清楚比较器

发布于 2024-11-02 22:13:27 字数 1519 浏览 1 评论 0原文

我正在尝试对数组列表进行排序,但我无法理解比较器。我不明白如何从从文本文件创建的数组列表中定义可排序字段。此外,我不确定比较器逻辑。在我看来,这就像创建一组比较器函数,然后调用它们。这是真的吗?

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

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);

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

I'm trying to sort an arraylist but I can't wrap my head around the comparator. I don't understand how to define sortable fields from my arraylist which is created from a text file. Furthermore I'm unsure of the comparator logic. It seems to me like create a set of comparator functions, and then later invoke them. Is this true?

So far my code looks like this:

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);

I appreciate any help anyone can give.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

诗酒趁年少 2024-11-09 22:13:27

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

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

如果元素“相等”,那么您可能希望按第二个字段排序,然后按第三个字段排序,并继续下去,直到排序顺序明确为止。

Complex 类的简单比较器,其中包含字段 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);
  }
});

Comparator logic is simple. When you sort an array of elements you have two choices - sort using the Comparable on each element (assuming there is one) or supply a Comparator. If your array contains complex elements or there are different sort criteria then the latter choice is probably what you need to use.

Each time the comparator is called you must say if element 1 is "less than" element 2 in which case return a negative number, element 1 is "greater than" element 3 in which case return a positive number. Otherwise if elements are equal return 0. You may also do reference and null comparison before comparing values so that null elements are logically "less than" non-null elements and so on.

If elements are "equal" then you may wish to sort by a secondary field and then a third field and keep going until the sort order is unambiguous.

A simple comparator for a class Complex which has fields a & b and we want to sort on 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);
  }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文