Reputation: 37
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??;
}
Upvotes: 0
Views: 2401
Reputation:
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();
}
}
Upvotes: 2
Reputation: 1032
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);
}
}
Upvotes: 0