Andrew Johnson
Andrew Johnson

Reputation: 31

How two swap two elements in a array list without using collections.swap method

Develop a method to swap two elements with specified valid indexes I and j:

public void swap(int I, int j);

This is the method I have to use to swap two of the elements in an array list. The original list is: [a ==> b ==> c ==> d............] After calling swap(0, 2): [c ==> b ==> a ==> d............] This is what should print out for the output.

--------- First class-----

package it179.pa2;

import java.util.*;

public class MyArrayList {

private String list;


MyArrayList(String list) {
    this.list = list;
}
MyArrayList() {

}

public void swap(int i, int j) {
    int temp1;
    temp1 = i;
    i = j;
    j = temp1;               
    }

@Override
public String toString() {
    return list + "==>";
}

}

----- Second Class-----

package it179.pa2;
import java.util.*;

public class MyArrayListTest {


public static final void main (String[]args) {

    MyArrayList my = new MyArrayList();


    ArrayList<MyArrayList> al = new ArrayList<MyArrayList>();

    al.add(new MyArrayList("A"));
    al.add(new MyArrayList("B"));
    al.add(new MyArrayList("C"));
    al.add(new MyArrayList("D"));
    al.add(new MyArrayList("E"));
    al.add(new MyArrayList("F"));
    System.out.print("The original list is: ");
            for (MyArrayList tmp: al) {

        System.out.print(tmp);      
    }// end of for

    System.out.println("After calling swap(0,2): ");
    System.out.print(al);
}

}

Upvotes: 2

Views: 14773

Answers (2)

L.Petrosyan
L.Petrosyan

Reputation: 440

For swap elements in List you can you swap() method of java.util.Collections

Collections.swap(list, element1, element2)

Upvotes: 2

NcAdams
NcAdams

Reputation: 2899

Here it is with a static method:

public static <E> void swap(List<E> list, int i, int j) {
    E e = list.get(i);
    list.set(i, list.get(j));
    list.set(j, e);
}

See this question. To do this using a class, the logic would be the same, but the method signature would instead be public void swap(int i, int j).

Upvotes: 2

Related Questions