0

The goal is to invert 2 elements of a List. Like if I have

List<Integer> integers = new List<Integers>{1,2,3,4,5,6,7};

If I call this method:

invert(List: integers, index1: 2, index2: 3);

It should return me:

List<Integer>{1,2,4,3,5,6,7};

I'm trying to use the .set() method, but seems like I've written it in a bad way. The code is the following:

 public static List<Integer> invert(List<Integer> integers, Integer index1, Integer index2)
{
        for(Integer counter = 0; counter < integers.size(); counter++)
        {
            if(integers.indexOf(counter) == integers.indexOf(index1))
            {
                integers.set(index1, integers[index2]);
            }
            else if(integers.indexOf(counter) == integers.indexOf(index2))
            {
                integers.set(index2, integers[index1]);
            }
            else
            {
                return null;
            }
        }
    return integers;
}

I'm not getting any kind of error and this method return the same list that I've initialized in the test class before calling the method. So I think it is not executing the .set() function, but I don't know why. Can someone explain and suggest me a possible solution?

Thank you so much in advance for your help.

1
  • You should edit your question to provide more details. If you're getting an error message, you should copy and paste it (do not try to paraphrase) into your question, and call out which line the error is complaining about. If you're not getting an error, you should provide us with some example input, the output you expect, and the output you're actually getting.
    – Derek F
    Sep 29, 2021 at 13:40

1 Answer 1

1

Swapping item positions in a list is a simple programming exercise.

The thing it looks like you're stuck on is that you can put the value of the first index into the second index, but in doing so you're losing the initial value of the second index. With your example, I'd expect the result to be [1, 2, 3, 3, 5, 6, 7]

...that is if you didn't introduce a bug with that else block in your for loop. return null; stops the execution of the method. If you want to skip any additional processing in a loop and just move on to the next iteration, you'd use continue;. If you want to get out of the loop but remain in the current method, you'd use break;. Neither of those are particularly useful here.

Unless you have a specific reason to implement the XOR swap algorithm, you'll need to store the initial value of your second index in another variable before you update its value (and then use that other variable to update the first index).

Since you have the target indices, you don't need to use a loop here (and doing so just wastes cpu time and increases the chance that you'll create a bug).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.