0

如何在下面的示例中找到第 4,1 和 6 行?
在这种情况下,将 Collection.sort() 与 Comparator 一起使用是否合理?

       a -  b - c - d

1.)    6    8   16  18   
2.)    38  40   55  57  
3.)    6    8   25  27  
4.)    1    5   11  15  
5.)    6    8    3   5  
6.)    9   12   19  22   
7.)    18  20    1   3  
8.)    23  25   15  17 

顶部的示例是一个对象满足以下条件的列表:
- 每个对象包含 4 个整数(a,b,c,d),
- 列表中的每个对象都是唯一的,
- a < b 和 c < d。


下面不是工作示例,而是我的思维方式,我可以期望比较器如何工作以找到预期的对象。

public class Row_Filter implements Comparable<Row_Filter>{
    int a,b,c,d;
    public Row_Filter(int a, int b, int c, int d) {
        this.a = a; this.b = b; this.c = c; this.d = d;
    }
   static class FilterAccordingAB implements Comparator<Row_Filter> {
        public int compare(Row_Filter o1, Row_Filter o2) {
            return o2.a - o1.b+1;
        }
    }
   static class FilterAccordingCD implements Comparator<Row_Filter> {
        public int compare(Row_Filter o1, Row_Filter o2) {
            return o2.c - o1.d+1;
        }
    }
   static class FilterAccordingABCD implements Comparator<Row_Filter> {
        public int compare(Row_Filter o1, Row_Filter o2) {
            FilterAccordingAB abF=null;    FilterAccordingCD cdF=null;
            if((abF.compare(o1, o2)==0) && (cdF.compare(o1, o2)==0)){
                return 1;
            }
            return -1;
        }
    }
} 
4

2 回答 2

3

你需要做的是实现一个 Comparator接口。查找该接口的 JavaDocs。您将需要编写一个实现该接口的类。这涉及编写一种方法(您不需要重新实现 equals())。

该方法传递了两个对象。根据您的要求,查看您需要从该方法返回什么值以显示两个对象“相等”。然后根据您的要求编写代码以在它们“相等”时返回该值。

如果其中任何一个不清楚,您将需要查找有关编写方法、编写类或使用接口的基本 Java 教科书。

于 2010-09-15T20:31:33.300 回答
0

您似乎对在哪里使用比较器感到困惑。DJClayworth 准确地描述了如何创建一个。例如,您将在排序机制中使用一个:

Collections.sort(myList, myComparator);

您使用它是因为您可以定义比较算法来对集合进行排序。希望这有助于澄清一些。

于 2010-09-15T20:33:33.057 回答