The first thing to be added to this queue should be an all-zero group, and the array {1,2,3,4,5} should be the last to be added. Why is it that {1,2,3,4,5} pops up after the poll method?
Asked
Active
Viewed 49 times
-2
-
2The `poll()` method _does_ return the first element of the queue. The "problem" is that you have added **the same array instance** 5 times to the queue (i.e., all elements are literally the same object in memory). Perhaps you thought objects were _pass-by-value_ in Java. That's not quite right. Java is indeed _pass-by-value_, but the "value" passed is the reference (i.e., the reference is copied, not the object). See [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/q/40480/6395627). – Slaw Jan 14 '23 at 04:59
-
2Also, please do not post images of code. See [Why should I not upload images of code/data/errors?](https://meta.stackoverflow.com/q/285551/6395627). – Slaw Jan 14 '23 at 05:02
1 Answers
1
That is because of Array's are mutable, its not about Queue operations. Whenever you will change any value in Array, it will be reflected every where that array is being used.
Please go through the below link to understand more on Array mutability - https://sebhastian.com/are-arrays-mutable-java/