I'm trying to write a method to quickly assign the contents of one int[] to the other. I think I might be having difficulty interpreting the problem because I don't think methods can perform assignment on a variable name provided as an argument. If the problem didn't say to write a method, I would probably just declare the temp int[] and perform the assignments in main. I added print loops to the switchThem method to show how the result differs from printing the contents in main after running the method.
Here's the text of the problem:
"Write a method called switchThem that accepts two integer arrays as parameters and switches the contents of the arrays. Take into account that the arrays may be of different sizes."
public class Ch8Scratch {
public static void main (String[] args) {
int[] first = { 1, 2, 3, 4, 5 };
int[] second = { 6, 7, 8 };
switchThem(first,second);
System.out.println();
for (int number : first) {
System.out.print(number + "\t");
}
System.out.println();
for (int number : second) {
System.out.print(number + "\t");
}
System.out.println();
}
public static void switchThem (int[] array1, int[] array2) {
int[] temp = array1;
array1 = array2;
array2 = temp;
for (int number : array1) {
System.out.print(number + "\t");
}
System.out.println();
for (int number : array2) {
System.out.print(number + "\t");
}
}
}
Output:
6 7 8
1 2 3 4 5
1 2 3 4 5
6 7 8