arrays - How to swap entries efficiently in an Integer ArrayList in java -


if have integer array, can use following efficient code switch elements 1 , 5, , print new array: (assume in main method, integer array {1,2,3,4,5}. when method below called upon, {5,2,3,4,1} returned)

        public static int[] switchends(int[] nums){         nums[0]=(nums[0]+nums[4])-(nums[4]=nums[0]);         return nums;         } 

can similar arraylist? tried following code (an exact copy of previous code using commands relevant arraylist):

       arraylist<integer> nums=new arraylist<integer>();        (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 left-hand side on line 3 has variable. understand error, cannot figure out how correct this.

finally, can similar string arrays? code below illustrates question:

       string[]a={"java","is","cool"};        a[0]=(a[0]+a[2])-(a[2]=a[0]);        return a; 

(i want obtain result {"cool","is","java"}) thanks!

use set modify value of arraylist:

nums.set(0, (nums.get(0)+nums.get(4))-(nums.set(4,nums.get(0)); 

however code hard understand , doubt (and additional arithmetics) worth saving single swap variable.

for strings, - operator not defined. use substring method. make more complicated.


Comments