Reputation: 37
Is it possible to create the following static void method in Java?
public static void reverse(LinkedList<String> linkedlist)
{
//Code would go here...
}
As I understand it, since Java is pass-by-value this isn't possible, correct?
Upvotes: 0
Views: 2518
Reputation: 3450
Java supports only pass by value but the code you posted will not make any error because it is also pass by value. refer these links Is Java "pass-by-reference" or "pass-by-value"?, Are Java function parameters always passed-by-value?, Immutable and pass by value, http://www.javaworld.com/javaqa/2000-05/03-qa-0526-pass.html
Upvotes: 1
Reputation: 234807
If you're talking about the stock java.util.LinkedList
class, then it's certainly possible to write such a method. In fact, there already is one: java.util.Collections.reverse(List<?> list)
that works with any modifiable list (including LinkedList
). It reverses the elements of the list.
If you're talking about a custom LinkedList
class, it depends on how the class is implemented. If a LinkedList
object is just a linked series of nodes with data, then no, you cannot reverse the list because you cannot change the first element; it would require changing what linkedList
references. You can do that internally in the method, but it won't affect the actual parameter in the calling code. That's the consequence of pass-by-value.
However, java.util.LinkedList
is not structured like that. The nodes are internal to the LinkedList
object itself. The object reference does not need to change to change the order of all the elements.
Upvotes: 1