Home > Software engineering >  How can I swap the values of specific indices of my List
How can I swap the values of specific indices of my List

Time:12-07

I have a List called myqueue and I'm trying to swap the values of two specific indexes in my List.

Here is what I have so far:

private Comparator<T> cc;
private List<T> myQueue;
   
private void exch(int i, int j) {  // helper method to exchange items at indices i and j
    T temp = this.myQueue.get(i) ;
    T temp1 = this.myQueue.get(j);
    this.myQueue.get(i) = temp1;
    this.myQueue.get(j) = temp;

}

However, there is a compilation error when I do this, which says "Variable expected". I'm confused on what I should do to resolve this. The first thoughts that come to my mind was to do this:

private void exch(int i, int j) {  // helper method to exchange items at indices i and j
    T temp = this.myQueue.get(i) ;
    T temp1 = this.myQueue.get(j);
    temp = temp1;
    temp1 = temp;
    temp = this.myQueue.get(i) ;
    temp1 = this.myQueue.get(j)

since I tried to use variables, but that would also not work as well. Can someone please help me resolve this issue?

CodePudding user response:

You are trying to use a get method to set a value.

If you read oracle documentation Oracle doc you can find that the get method only return values, you could use set method and the index that you want to change to modify the list

  • Related