Michal
Michal

Reputation: 13

Generic type and own comparator

I have problem with generic type in priority queue and my comparator because I don´t know how to retype.

When I call compare(IRecord t, IRecord t1)` method, it wants IRecord object, but I need compare generic type.

Class AbstrPriorQueue must be generics.

There is a comparator which works with object IRecord:

public class MyComparator implements Comparator<IZaznam> {

@Override
public int compare(IRecord t, IRecord t1) {
    if (t.getPriority() < t1.getPriority()) {
        return -1;
    } else if (t.getPriority() > t1.getPriority()) {
        return 1;
    } else {
        return 0;
    }
  } 
}

And this is my shortened priory queue. I give comparator in constructor. IAbstrPriorQueue is only interface.

public class AbstrPriorQueue<T> implements IAbstrPriorQueue<T> {
    // comparator
    private MyComparator myComparator;

    public AbstrPriorQueue(MyComparator myComparator) {
          this.myComparator = myComparator;
    }

    @Override
    public void insert(T data) {
          T temp = list.getLast();

          // there is a error (no suitable method found for compare(T,T))
          if (myComparator.compare(data, temp) <= 0) {
                // ....
          }
    }
}

Do you know what can I do?

Upvotes: 0

Views: 94

Answers (1)

GhostCat
GhostCat

Reputation: 140427

There is a misconception on your end: you can't use a fixed comparator for elements of an unknown generic type!

You have have a comparator that only works for apples; but you want to use it within a box that accepts all kinds of things. How is that apple comparator supposed to know how to compare bananas? Or eggs?

So; one potential way would be to change your "box" to accepts only apples.

public class AbstrPriorQueue<T extends IZaznam> 

for example.

Meaning: you have to make clear that your queue only takes things that are IZaznams. Or you can't use that specific comparator. One way or the other. You can't have it both ways.

But most likely, you want it the other way round: by using a comparator that is also generic:

public class AbstrPriorQueue<T> ... {
  private final Comparator<T> komparator;
  ...

You see, there is actually no need to fix the type of comparator on this level!

And now you can go for:

AbstrPriorQueue<IZazname> izazies = new AbstrPriorQueuey<>(new Komparator());

Upvotes: 2

Related Questions