Wednesday, July 30, 2014

A shuffle method for array lists

It so happens that there is a method in Java specifically designed to shuffle array lists called, surprisingly, shuffle. Here is some code that enters items into an arrayList and then calls the shuffle method. the shuffle method is in the Collections library.

First here is my Item class that has one property "name."

package com.sponger.RandomizeArray;

public class Item {
 private String name;
 
 public Item(String name){
  setName(name);
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}

Now here is the Program class that creates an ArrayList of Items and then shuffles them

package com.sponger.RandomizeArray;

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

public class Program {

 public static void main(String[] args) {
  Program p = new Program();
  p.createArray();

 }
 
 private void createArray(){
  ArrayList<Item> myArray = new ArrayList<Item>();
  Item i = new Item("one");
  Item i2 =new Item("two");
  Item i3 =new Item("three");
  Item i4=new Item("four");
  Item i5=new Item("five");
  myArray.add(i);
  myArray.add(i2);
  myArray.add(i3);
  myArray.add(i4);
  myArray.add(i5);
  
  shuffle(myArray);
 }
 
 private void shuffle(ArrayList<Item> list){
  Collections.shuffle(list);
  
  for(Item i: list){
   System.out.println(i.getName());
  }
 }

}


After the shuffle it came out

four
two
five
one
three

No comments:

Post a Comment