Collections

Shuffle elements of Java ArrayList example

Want to learn quickly?
Try one of the many quizzes. More than Java 400 questions with detailed answers.

Add Comment

  • An alternative implementation..

    static <t> ArrayList<t> shuffleRight(ArrayList<t> list,int positions){

    ArrayList<t> newList = new ArrayList<t>();
    for (int i = 0; i < positions; i++) {
    list.remove(list.size()-1);
    }
    for (int i = 0; i < positions; i++) {
    newList.add(i, (T)new Integer(0));
    }
    for (int i = 0; i < list.size(); i++) {
    newList.add(list.get(i));
    }

    return newList;

    }
    static <t> ArrayList<t> shuffleLeft(ArrayList<t> list,int positions){

    ArrayList<t> newList = new ArrayList<t>();
    for (int i = 0; i < positions;++i) {
    list.remove(0);
    }
    for (int i = 0; i < list.size(); i++) {
    newList.add(list.get(i));
    }
    for (int i = 0; i < positions; i++) {
    newList.add((T)new Integer(0));
    }

    return newList;

    }

Sponsors

Facebook Fans

Online Shopping – Flipkart