Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to exchange elements in an ArrayList without using any predefined functions is by using a temporary variable.

Here is an example code snippet:

// swapping elements at index i and j in myList ArrayList
int i = 1;
int j = 3;

// using temporary variable to exchange elements
Object temp = myList.get(i);
myList.set(i, myList.get(j));
myList.set(j, temp);

In the above code, we first define the indices of the elements that we want to swap (i and j). Then, we use a temporary variable (temp) to hold the value at index i before we overwrite it with the value at index j. Finally, we set the value at index j to be the value of temp, which is the original value at index i. This way, we have effectively swapped the values at indices i and j.