javadata-structuresqueue

Add an ArrayList into a Queue (LinkedList)


As I know, we can make create a Queue using syntax along the lines of Queue<Integer> = new LinkedList<>().

But when I try to add the ArrayList<Integer> element into the Queue<Integer> with the .add() method, it doesn't work.

I was considering two solutions to fix this issue:

  1. Use Queue<ArrayList<Integer>> instead of Queue<Integer>
  2. Use Queue<Integer> and add the ArrayList by Queue.addAll()

Which of these should I use?


Solution

  • Your two implementations do very different things.

    Option 1 is for when you want to create a Queue of ArrayLists. In this case, each item in the queue would be a complete list, and adding a new item with .add would append one whole list to the queue. A Queue<ArrayList<Integer>> would give you a 2D structure like this:

    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    

    Option 2 is for when you want to create a Queue of Integers. In this case, each item in the queue would be an individual number, and "adding" a list with .addAll would append each item in the list to the queue sequentially. This method would give you a 1D structure like this:

    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Which one is "better" depends on your use case - it's beyond the scope of this site to give you a specific recommendation given the limited information you've provided.