Chase S
Chase S

Reputation: 15

Java sorting program

This is my first post so please excuse me if I've made any errors.

In this program I've written, the user inputs integers one at a time from the keyboard, 2 4 5 1 3 for example. The reverse method if called before any of the others would return 3 1 5 4 2. However, if the sort method is called, giving us 1 2 3 4 5, then the reverse method is called, we get 5 4 3 2 1. Any ideas how to get the reverse to return the reverse order of the original input even after the other methods have been called?

   public static void reverse(ArrayList<Integer> num) {
        ArrayList<Integer> newNum= new ArrayList<Integer>();
        newNum = num;   

        Collections.reverse(newNum);
        System.out.println(newNum); 
    }

Upvotes: 0

Views: 192

Answers (4)

Michael W
Michael W

Reputation: 65

In each of your methods when you call newNum = num, you are giving up the reference to the array list you just "newed" and pointing newNum at the memory location of "num" (or doing what is called a "shallow copy." Anything that you do to newNum is being done to num, and vice versa.

Instead you want to make a "deep copy" of your num array. I'd suggest replacing the first two lines of each method with a call to a private method doing something like this:

private ArrayList<Integer> copyList(ArrayList<Integer> in) { 
    ArrayList<Integer> out = new ArrayList<Integer>();
    for (int i : in) {
        out.add(i);
    }
    return out;
}

Though I haven't checked that for correctness.

Good luck!

Upvotes: 0

Lokathor
Lokathor

Reputation: 1014

You have to make a copy of what the user input before you start messing with it if you want to save it for later.

public static void main(String[] args) {

ArrayList<Integer> num = new ArrayList<Integer>();
ArrayList<Integer> numStartingList; 

//stuff about reading the variable in here

numStartingList = new ArrayList<>(num); 

// read options and show output
}

Upvotes: 1

Joe F
Joe F

Reputation: 4252

Every time you do this:

newNum = num;

You are making newNum point to the same ArrayList as num. Any changes you make to either newNum or num will be reflected in the other. They are the same ArrayList instance.

You probably want to construct a new ArrayList instance containing the same elements.

ArrayList<Integer> newNum = new ArrayList<Integer>(num);

Upvotes: 2

Menelaos
Menelaos

Reputation: 25725

Why not have two arraylists... One with the result of the last operation, and one with the original set as given. Therefore, result will always change and the original will stay the same.

Upvotes: 1

Related Questions