[英]Unchecked call error with generics and Java8 Streams
I've got an odd warning from my IDE, but the code still runs fine. 我的IDE发出了奇怪的警告,但是代码仍然可以正常运行。
The code is 该代码是
class TaskQueue<T extends Comparable> {
private final PriorityQueue<QueueItem<T>> queue =
new PriorityQueue<>(Comparator.comparing(QueueItem::getDeadline));
}
The IDE gives me a warning and an error: IDE给我一个警告和一个错误:
Warning 警告
Unchecked call to 'PriorityQueue(Comparator<? super E>)' as a member of raw type 'java.util.PriorityQueue'
Error referring to QueueItem::getDeadline
错误指的是QueueItem::getDeadline
Non-static method cannot be referenced from a static context
I'm new to Java and, altough the code works, I'd like to know if I can write it in a better way or if there is a proper way. 我是Java的新手,虽然代码可以正常工作,但我想知道是否可以用更好的方式编写它,或者是否有适当的方法。
Thank you 谢谢
The code for QueueItem
QueueItem
的代码
class QueueItem<T extends Comparable>{
private final T deadline;
QueueItem(T deadline) {
this.deadline = deadline;
}
T getDeadline() {
return deadline;
}
}
Shouldn't that QueueItem
look a bit different(same goes for TaskQueue): QueueItem
看起来应该不一样(TaskQueue也一样):
QueueItem<T extends Comparable<T>>
notice the T extends Comparable<T>
注意T extends Comparable<T>
Comparable is a generic type, but in your code you did not specify the type of that Comparable
; Comparable是一种通用类型,但是在您的代码中,您没有指定该Comparable
的类型; instead it is raw. 相反,它是原始的。
The method QueueItem::getDeadline
return some kind of object that does not implement Comparable
. 方法QueueItem::getDeadline
返回不实现Comparable
某种对象。
So the solution will be: 因此解决方案将是:
class Deadline implements Comparable<Deadline> {
@Override
public int compareTo(Deadline o) {
return 0 /* Some comparing logic here */;
}
}
And the Comparator.comparing
expects something that returns Comparable
object. 并且Comparator.comparing
期望返回的是Comparable
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.