簡體   English   中英

使用抽象類時如何使用比較器?

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

我嘗試使用compareTo並實現Comparable的接口,但我找不到比較兩個對象的方法,以便它返回一個整數(如果第一個對象小於第二個,則為 -1,如果它們相等則為 0 並且如果對象 1 大於對象 2,則為 1)。 這是我嘗試過的:

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

我基本上是在嘗試使用可比較的方法對 MyArrayList 進行排序。 你知道我有什么其他方法可以比較兩個對象嗎? 謝謝!

您只需要接受實現Comparable接口的類。

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

之后,您需要將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