1

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

Is it not allowed to have values of multiple types in a single PriorityQueue? What could be the other way around?

My PriorityQueue looks like this:

PriorityQueue queue = new PriorityQueue();

Element to add is as following:

public void addElementToQueue(Object obj) {
        queue.add(obj);
}
Hubi
  • 440
  • 1
  • 11
  • 25
Priyesh
  • 131
  • 1
  • 1
  • 12
  • [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/q/2770321/5221149) – Andreas Dec 17 '19 at 14:11
  • 1
    Use the [`PriorityQueue(Comparator super E> comparator)`](https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html#PriorityQueue-java.util.Comparator-) constructor to create a `PriorityQueue`, using a `Comparator` of your own implementation that knows how to compare a `String` with an `Integer`. – Andreas Dec 17 '19 at 14:12
  • Two questions - 1. Why do you want to add String and Integers in the same Queue? 2. Can you share complete code and stacktrace etc? – Anand Vaidya Dec 17 '19 at 14:13
  • *Curious:* What comes first, `Foo` or `42`? – Andreas Dec 17 '19 at 14:13
  • @Andreas: I added the string values first and then the integer one. – Priyesh Dec 17 '19 at 14:41
  • 1
    if i add the following data: priorityQueue.add("Foo"); priorityQueue.add("Bar"); priorityQueue.add(2); priorityQueue.add(1); priorityQueue.add(3); priorityQueue.add(4); What do you expect in the response ? – Alejandro Agapito Bautista Dec 17 '19 at 16:15
  • @Priyesh I wasn't asking about the order you add values to the queue, but in what *priority order* you want the values *returned*, e.g. which has higher priority, `Foo` or `42`? – Andreas Dec 17 '19 at 21:27

1 Answers1

0

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