-1

This seems very simple but I can't quite figure out why this isn't working.

I want to reverse the elements in my LinkedList which I have a working method for, but I can't return the value as my prof wants it to be a void method. How would I go about this?

import java.util.LinkedList;
public class ListUtil {
    public static void reverse(LinkedList<String> strings) {
        LinkedList<String> reverseLinkedList = new LinkedList<>();
        for(int i = strings.size() - 1; i >= 0; i--) {
            reverseLinkedList.add(strings.get(i));
        }
        strings = reverseLinkedList;
        System.out.println(strings);
    }
}
import java.util.LinkedList;

public class ReverseTester {
    public static void main(String[] args) {
        LinkedList<String> employeeNames = new LinkedList<>();
        employeeNames.addLast("Dick");
        employeeNames.addLast("Harry");
        employeeNames.addLast("Romeo");
        employeeNames.addLast("Tom");
        
        ListUtil.reverse(employeeNames);
        System.out.println(employeeNames);
        System.out.println("Expected: [Tom, Romeo, Harry, Dick]");
    }
}

In my ListUtil class, it does reverse the list, but doesnt return a value (as it is void) but I don't know how to go about setting employeeName in the ReverseTester class.

I know this is probably super simple but I have not been able to figure this out for the life of me, any help is greatly appreciated.

  • Reverse it in-place? – Dave Newton Mar 26 '21 at 03:29
  • @Dave Newton I wish I could, it would be way easier, or even if I could make the method return a Linked List back, but my prof does not want that sadly – Ryan Farewell Mar 26 '21 at 03:30
  • maybe copy/clone your current LinkedList to the new one, then travel in the original one to do the reverse, doing so you do not need to return as the original would be reversed – Hưng Chu Mar 26 '21 at 03:33
  • @HưngChu are you talking about copying the LinkedList into the other class? – Ryan Farewell Mar 26 '21 at 03:37
  • [`Collections.reverse( list )`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collections.html#reverse(java.util.List)) – Basil Bourque Mar 26 '21 at 03:38
  • @BasilBourque that worked! Thanks, any chance you could explain why this works? – Ryan Farewell Mar 26 '21 at 03:40
  • @RyanFarewell Why it works?? Just look at the [source code at the OpenJDK project](https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/Collections.java). Also, my comment was in jest. I am sure that as a schoolwork assignment you should be doing it the hard way, writing your own code for the reversing. – Basil Bourque Mar 26 '21 at 03:43
  • @BasilBourque ah ok. Yeah I assumed so, the code I wrote does reverse the list but it doesn't change the LinkedList in the tester class where I sent the list. I was really just trying to figure out how to connect the two. – Ryan Farewell Mar 26 '21 at 03:46
  • The problem is that your method creates a new list object, assigning that new one to the *local* reference (pointer), while the reference/pointer in the calling code still points to the original list object. So your called method must work *within* the existing list (if you cannot return a fresh new list). Notice how the [Answer by saka1029](https://stackoverflow.com/a/66810695/642706) clears the existing list and refills it, rather than *replacing* the original list. Your underlying lesson is probably about Java being [pass-by-value](https://stackoverflow.com/q/40480/642706) not by-reference. – Basil Bourque Mar 26 '21 at 03:56
  • @BasilBourque you are amazing you know that! I didn't even realize that would affect it. Really appreciate the help! All the best. – Ryan Farewell Mar 26 '21 at 04:00
  • I added some text to the [Answer by saka1029](https://stackoverflow.com/a/66810695/642706) with the points from my comment. Hopefully I did not ruin the Haiku-like simplicity of that very good Answer. – Basil Bourque Mar 26 '21 at 04:04
  • @BasilBourque Thanks so much for making it clear! Have yourself a great night. – Ryan Farewell Mar 26 '21 at 04:09
  • @RyanFarewell So you *did* want it reversed in-place? – Dave Newton Apr 28 '21 at 13:01

2 Answers2

1

Empty and re-fill the existing list rather than replacing it.

public static void reverse(LinkedList<String> strings) {
    List<String> temp = new ArrayList<>(strings);   // Copy the contents of the original list. Pass the original list to constructor of our duplicate list.
    strings.clear();                                // Empty the original list.
    for (String e : temp)
        strings.addFirst(e);                        // Refill the original list using elements from our duplicate list.
}

Or simply

public static void reverse(LinkedList<String> strings) {
    Collections.reverse(strings);
}
Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
saka1029
  • 13,523
  • 2
  • 13
  • 37
0

Non-primitive Java object are stored by reference so you don't need to return anything from ListUtil::reverse. Any changes made to the object in the function will be reflected in ReverseTester.java. This happens because, again, non-primitive Java objects are stored by reference. Basically your code does exactly what you want it to do. You make a LinkedList, populate it with items, and then reverse those items.

You will have a problem with System.out.println(employeeNames); though. Because that will just print the object's formal name and not it's contents. If you want to print the contents of a list in Java you can do:

for (String name : employeeNames) {
    System.out.println(t);
}

This is my first answer so please ask any questions if I wasn't clear enough!

Braden
  • 1
  • ```System.out.println(employeeNames);``` is what my prof wants and expects it to print out the list in reverse. That's very helpful though, I was not aware of non-primitave objects and how they work. I had used the for loop on an above answer which did reflect back to my tester class. – Ryan Farewell Mar 26 '21 at 03:51
  • very clear answer! I'm still relatively new to Java and just didn't understand some of the reasonings behind why thinks work. You cleared up everything! – Ryan Farewell Mar 26 '21 at 03:52