简体   繁体   English

使用抽象类时如何使用比较器?

[英]How to use a comparator when working with abstract classes?

I've tried to use compareTo and implementing the interface of Comparable but I cannot find a way to compare two objects so that it returns an integer (-1 if the first object is smaller than the second one, 0 if they're equals and 1 if object 1 is greater than object 2).我尝试使用compareTo并实现Comparable的接口,但我找不到比较两个对象的方法,以便它返回一个整数(如果第一个对象小于第二个,则为 -1,如果它们相等则为 0 并且如果对象 1 大于对象 2,则为 1)。 This is what I've tried:这是我尝试过的:

public class MyArrayList<E> {

private Object[] array;
private int size;
private int capacity;

public MyArrayList() {
    this.capacity = 1000;
    this.array = new Object[capacity];
    this.size = 0;
}

public boolean add(E element) {
int i = 0;
while(element.compareTo(array[i]) > 0) {
    i++;
    }
this.set(i, element);
return true;
  }
}

I'm basically trying to sort my MyArrayList using a comparable.我基本上是在尝试使用可比较的方法对 MyArrayList 进行排序。 Do you have any idea what other ways I have to compare both objects?你知道我有什么其他方法可以比较两个对象吗? Thanks!谢谢!

You need to only accept classes that implements the Comparable interface.您只需要接受实现Comparable接口的类。

public class MyArrayList<E extends Comparable<E>> {

After that, you'll need to cast the parameter inside your compareTo call to E , since the array is of Object type.之后,您需要将compareTo调用中的参数转换为E ,因为arrayObject类型。

public boolean add(E element) {
    int i = 0;
    while (element.compareTo((E) array[i]) > 0) {
        i++;
    }
    this.set(i, element);
    return true;
}

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

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