rakeeee
rakeeee

Reputation: 1073

Arraylist(even/odd) swapping elements java

Hello folks, I am just trying to swap the list items irrespective of the odd or even list. I sense there might be another way of doing swap when the list size is odd. i am just patching the code based on the errors i see on console. Is there any better way to swap the list items when the list is odd not with if condition inside the else.

package org.ada.crm;

import java.util.ArrayList;
import java.util.Collections;

public class AList {

    public static void main(String[]args){
        String[] num = {"four", "score", "and", "seven", "years", "ago","sure"};
        ArrayList<String>list = new ArrayList<String>();
        for(int i=0;i<num.length;i++){
            list.add(num[i]);
        }
        System.out.println("****hhh"+list);
        swapPair(list);
    }

    private static void swapPair(ArrayList<String> list) {

        int listsize = list.size();
        for(int i=0;i<listsize;i+=2){
        if(listsize%2==0){
            Collections.swap(list, i, i+1);
        }else{
            if(i+1<listsize) ///here i want to know is there any better solution
                Collections.swap(list, i, i+1);
        }}
        System.out.println("jfsfjdsl"+ list);
    }

}

Upvotes: 0

Views: 746

Answers (2)

Radiodef
Radiodef

Reputation: 37845

If you just want something interesting, here is a nifty way.

  • If a binary number is even, the last bit is 0.
  • If a binary number is odd, the last bit is 1.

So you get the last bit, then subtract it from the list size.

  • For even list size: listSize = listSize - 0.
  • For odd list size: listSize = listSize - 1.
private static void swapPair(List<String> list) {
    int listSize = list.size();
    listSize -= listSize & 1;

    for(int i = 0; i < listSize; i += 2) {
        Collections.swap(list, i, i + 1);
    }
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201477

I think you are looking for a combination of Arrays.asList(T...) and Collections.shuffle(List) like

String[] num = {"four", "score", "and", "seven", "years", "ago","sure"};
List<String> list = new ArrayList<>(Arrays.asList(num));
Collections.shuffle(list);
System.out.println(list);

Upvotes: 1

Related Questions