简体   繁体   中英

Java - Static Void Method - LinkedList - Pass By Value

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM