[英]How can i add elements to a PriorityQueue of Java Collections that are of different type?
I want to add string and integer elements into a Priority Queue.我想将字符串和整数元素添加到优先队列中。 However,after adding string elements and then integer, the program breaks and gives me error as following: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
但是,在添加字符串元素和整数后,程序中断并给出如下错误: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
Is it not allowed to have values of multiple types in a single PriorityQueue?是否不允许在单个 PriorityQueue 中具有多种类型的值? What could be the other way around?
反过来又是什么?
My PriorityQueue looks like this:我的 PriorityQueue 如下所示:
PriorityQueue queue = new PriorityQueue();
Element to add is as following:要添加的元素如下:
public void addElementToQueue(Object obj) {
queue.add(obj);
}
I don't know know what logic do you want to follow but it will look like the following code:我不知道你想遵循什么逻辑,但它看起来像下面的代码:
public static void main(String[] args) {
PriorityQueue<Object> priorityQueue = new PriorityQueue<>(new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
//Your own comparison logic
return 0;
}
});
priorityQueue.add("Bar");
priorityQueue.add(2);
priorityQueue.add(1);
priorityQueue.add(3);
priorityQueue.add(4);
priorityQueue.add("Foo");
System.out.println(priorityQueue);
}
Please let me know if you need more details.如果您需要更多详细信息,请告诉我。
Thanks谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.