[英]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. 当我调用compare(IRecord t,IRecord t1)方法时,它需要IRecord对象,但是我需要比较泛型类型。
Class AbstrPriorQueue must be generics. 类AbstrPriorQueue必须是泛型。
There is a comparator which works with object IRecord: 有一个与对象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.
IAbstrPriorQueue是唯一的接口。
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? 你知道我能做什么吗?
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. 含义:您必须明确说明您的队列仅包含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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.