How to create a Queue which accepts any Datatype?

Tags: , ,



How to insert both String’s and Integers in the same Queue ?

Please look at the below program, I have created two objects (q, q1). Can we insert strings and integers in one Queue?

import java.util.*;
public class Solution {
   public void myMethod() {
      Queue<Integer> q=new PriorityQueue<>();
      Queue<String> q1=new PriorityQueue<>();
      q.add(3);
      q1.add("Eswar");
      System.out.println(q);
      System.out.println(q1);
   }

   public static void main(String...args) {
      Solution s=new Solution();
      s.myMethod();
   }
}

Answer

Using a Queue<Object> you’ll be able to add any type you want, becauseObject is a supertpe of every one. But you cannot use any implementation, like PriorityQueue because it requires a sort on the elements, and different types are not comparable together. An ArrayDeque would be good for that.

Queue<Object> q = new ArrayDeque<>();
q.add(5);
q.add("Foo");
q.add(5d);

Workable Demo



Source: stackoverflow