简体   繁体   English

Java - 静态空方法 - LinkedList - 按值传递

[英]Java - Static Void Method - LinkedList - Pass By Value

Is it possible to create the following static void method in Java? 是否可以在Java中创建以下静态void方法?

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? 据我所知,由于Java是按值传递的,这是不可能的,对吗?

If you're talking about the stock java.util.LinkedList class, then it's certainly possible to write such a method. 如果你在谈论库存java.util.LinkedList类,那么编写这样的方法肯定是可能的。 In fact, there already is one: java.util.Collections.reverse(List<?> list) that works with any modifiable list (including LinkedList ). 事实上,已经存在一个: java.util.Collections.reverse(List<?> list) ,它适用于任何可修改的列表(包括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. 如果您正在讨论自定义LinkedList类,则它取决于类的实现方式。 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; 如果LinkedList对象只是一个带有数据的链接系列节点,那么不能,你不能反转列表,因为你不能改变第一个元素; it would require changing what linkedList references. 这需要改变什么linkedList引用。 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. 但是, java.util.LinkedList的结构不是这样的。 The nodes are internal to the LinkedList object itself. 节点是LinkedList对象本身的内部。 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. Java仅支持按值传递,但您发布的代码不会产生任何错误,因为它也是按值传递的。 refer these links Is Java "pass-by-reference" or "pass-by-value"? 引用这些链接是Java“pass-by-reference”还是“pass-by-value”? , Are Java function parameters always passed-by-value? Java函数参数是否始终按值传递? , Immutable and pass by value , http://www.javaworld.com/javaqa/2000-05/03-qa-0526-pass.html 不变和传递价值http://www.javaworld.com/javaqa/2000-05/03-qa-0526-pass.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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