If I have an integer array, I can use the following efficient code to switch elements 1 and 5, and print the new array: (assume that in the main method, the integer array is {1,2,3,4,5}. So when the method below is called upon, {5,2,3,4,1} is returned)
public static int[] SwitchEnds(int[] nums){
nums[0]=(nums[0]+nums[4])-(nums[4]=nums[0]);
return nums;
}
Can I do something similar for ArrayList? I tried the following code (an exact copy of the previous code but using commands relevant to ArrayList):
ArrayList<Integer> nums=new ArrayList<Integer>();
for (int i=1;i<=5;i++){nums.add(i);}
nums.get(0)=(nums.get(0)+nums.get(4))-(nums.get(4)=nums.get(0));
The error is that the left-hand side on line 3 has to be a variable. I understand this error, but I cannot figure out how to correct this.
Finally, can I also do something similar for String arrays? The code below illustrates this question:
String[]a={"java","is","cool"};
a[0]=(a[0]+a[2])-(a[2]=a[0]);
return a;
(I want to obtain the result {"cool","is","java"}) Thanks!