0

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?

user2297661
  • 27
  • 1
  • 3
  • 1
    Have you tried to code this to see what happens before posting here? A LinkedList is a *reference* variable and therein lies all the difference. My suggestion: try it first. This site makes a poor substitute for your very own Java compiler. – Hovercraft Full Of Eels Apr 19 '13 at 03:46
  • 1
    Hint: There's a static method `Collections.reverse(List> list)` that works for any kind of modifiable list, including `LinkedList`. – Ted Hopp Apr 19 '13 at 03:49
  • When dealing with **objects** Java passes by value **their references**. It even creates an impression that Java passes objects by reference. – PM 77-1 Apr 19 '13 at 03:54
  • @PM77-1: Well, you don't really "deal with objects" in Java. You deal with references. – newacct Apr 19 '13 at 09:49
  • I think the best way to verify the question is: ---------- Have a try in you IDE like eclipse. If it doesn't throw exception ,Codes are right. Otherwise something wrong. ---------- – Peter Seng Apr 19 '13 at 03:55
  • "doesn't throw exception" is not exactly a complete test that the code is correct. – Ted Hopp Apr 19 '13 at 03:56

2 Answers2

1

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.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
1

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

Community
  • 1
  • 1
Visruth
  • 3,430
  • 35
  • 48