I have a very small program:
public static void main(String[] args) {
Queue<String> queue = new LinkedList<String>();
queue.add("one");
queue.add("two");
queue.add("tree");
printQueue(queue);
customizeQueue(queue);
printQueue(queue);
}
private static void customizeQueue(Queue<String> queue) {
queue.add("four");
queue.add("five");
printQueue(queue);
}
private static void printQueue(Queue<String> queue) {
for(String s: queue){
System.out.print(s + " ");
}
System.out.println();
}
I’m expecting an output of:
one two tree
one two tree four five
one two tree
However I’m getting:
one two tree
one two tree four five
one two tree four five
I’m not sure why this is happening. Am I passing the reference of the LinkedList instance? Can somebody please clarify why I’m not getting my expected output.
All types are passed by value in Java. However, what you are passing is not the object, but the reference to the object. This means that a copy of your whole queue is not created when you pass the reference, instead only a copy of the reference is created. The newly created reference still belongs to the same object and therefore when you do a
queue.add(), elements are added to the real object. On the other hand, reassigning the reference in the functionqueue = new LinkedLIst<String>()would have had no effect on the reference in the calling function.