ColoChr
ColoChr

Reputation: 1

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). 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. Do you have any idea what other ways I have to compare both objects? Thanks!

Upvotes: 0

Views: 443

Answers (1)

Mateus Bandeira
Mateus Bandeira

Reputation: 457

You need to only accept classes that implements the Comparable interface.

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.

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

Upvotes: 2

Related Questions