java 如何在外部泛型方法中寻址类的Comparator?

5us2dqdw  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(140)

我正在研究如何使用比较器来执行基于不同字段的比较。因此我创建了一个类Event,其中包含两个Comparator。

  1. class Event {
  2. int x, y;
  3. boolean isLeft;
  4. int index;
  5. Event(int x, int y, boolean isLeft, int index) {
  6. this.x = x;
  7. this.y = y;
  8. this.isLeft = isLeft;
  9. this.index = index;
  10. }
  11. public static <T extends Comparable> T[] quickSort(T[] a, int fst, int last, Comparator<T> comp) {
  12. int left = fst;
  13. int right = last;
  14. int middle = (last + fst) / 2;
  15. T x = a[middle];
  16. do {
  17. while (comp.compare(a[left], x) < 0) left++;
  18. while (comp.compare(a[right], x) > 0) right--;
  19. if (left <= right) {
  20. T temp = a[right];
  21. a[right] = a[left];
  22. a[left] = temp;
  23. left++;
  24. right--;
  25. }
  26. } while (left <= right);
  27. if (left < last) {
  28. quickSort(a, left, last, comp);
  29. }
  30. if (fst < right) {
  31. quickSort(a, fst, right, comp);
  32. }
  33. return a;
  34. }
  35. static class XComparator implements Comparator<Event> {
  36. @Override
  37. public int compare(Event e1, Event e2) {
  38. return (e1.x < e2.x) ? -1 : (e1.x > e2.x) ? 1 : (e1.y < e2.y) ? -1 : 1;
  39. }
  40. }
  41. static class YComparator implements Comparator<Event> {
  42. @Override
  43. public int compare(Event e1, Event e2) {
  44. return (e1.y < e2.y) ? -1 : (e1.y > e2.y) ? 1 : (e1.x < e2.x) ? -1 : 1;
  45. }
  46. }
  47. }

当我将Comparator传递给另一个类的泛型方法时,问题就出现了。我为valuecurrent.value以及Comparator提供的泛型类型的冲突如下:
“Event.YComparator”中的“compare(Event,Event)”不能应用于“(T,T)”

  1. Node Rec(Node current, T value, Event.YComparator comp) {
  2. if (current == null) {
  3. size++;
  4. current = new Node(value);
  5. return current;
  6. }
  7. else if (comp.compare(value, current.value) < 0) {
  8. current.leftChild = Rec(current.leftChild, value, comp);
  9. } else if(comp.compare(value, current.value) > 0) {
  10. current.rightChild = Rec(current.rightChild, value, comp);
  11. } else {
  12. return current;
  13. }

但我找不到解决方案,因为比较器是特定的,应该绑定到一个类(它们使用它的字段)。
我需要对这个问题的任何见解。

nkhmeac6

nkhmeac61#

我觉得你的设计有点混乱和过于复杂。所以这里有一些建议。

  • 定义一个具有static quickSort方法的QuickSort类。
  • 定义一个Node类(或记录),它具有要排序的数据类型。这样做可以更容易地指定多个Comparator选项,并且还可以对具有不同值和类型的节点列表进行快速排序。
  • 首先,让quickSort在没有指定比较器的情况下工作。
  • 然后,使用Comparator interface的比较器使其工作。尝试不同的选项,如reverseOrder()thenComparing()etc

除非你必须实现自己的比较器,否则你可以在这里停止。否则,既然一切都正常,你可以专注于你的比较器,这极大地限制了任何开发错误的起源。
我会从以下内容开始:

  1. record Node(int data1, int data2) {
  2. }
  3. class QuickSort {
  4. public static void quickSort(Node[] nodes, int low, int high,
  5. Comparator<Node> comp) { //initially, comp can be ignored.
  6. ...
  7. }
  8. }

您的集成比较方法可能是这样的。最终被通过quickSort方法传递的方法所取代。请注意,这种方法的问题是它使用固定的类型和数量。因此它限制了您可以排序的内容。

  1. public static int compare(Node n1, Node n2) {
  2. int a = n1.data1();
  3. int b = n2.data1();
  4. return a > b ? 1 : a < b ? -1 : 0;}
  5. }
展开查看全部

相关问题