0

I'm working on a method that carries out a variety of tasks for an array of integers. The methods include things like shifting all the elements to the right, swapping the first and last, and replacing elements with 0. I was able to successfully create methods for all of those things, but I would like to create a method that essentially 'resets' the array to its original values so I can test each of the other methods from the same set of numbers.

In other words:

prints: The original array is: 1, 2, 3

prints with swap method I made: The array with the first and last numbers swapped is: 3, 2, 1

array.reset()

prints with add method I made: The array with 6 & 7 added to the end is: 1, 2, 3, 6, 7


Here is the beginning of my method with my first attempt at a 'reset' method. I'm a bit lost as to how to set it up since everything I tried produced an error and I just seemed to be going in circles for such a ~seemingly~ simple method. Any ideas?

public class Ex2 {
private int[] values;
public Ex2(int [] initialValues) {values = initialValues;}

public void reset(){
    int[] values = values??;
}

2 Answers 2

2

You need to make a copy of the source array. Please note that this method works for primitive arrays, but for arrays of non-primitives, you will need to use System.arrayCopy() instead.

public class Ex2 {
  private int[] values;
  private int[] savedState;
  public Ex2(int [] initialValues) {
    values = initialValues;
    savedState = initialValues.clone();
  }

  public void reset(){
    values = savedState.clone();
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can make a copy of initialValues in your constructor. the code would be look like this:

public class Ex2 {
    private int[] values;
    private int[] originValues;

    public Ex2(int [] initialValues) {
        values = initialValues;
        System.arraycopy(values, 0, originValues, 0, values.length);
    }

    public void reset(){
        System.arraycopy(originValues, 0, values, 0, originValues.length);
    }
}

2 Comments

Arrays are references: this will not work. You are accessing the same array using two different references.
@JohnGaughan thanks for pointing out my mistake :) then we can use array copy to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.