Monday, 17 February 2014

Generic Random Picker in Java

Introduction

There are times that you have a list/an array of objects and you want to randomly pick one of them. The implementation for this is simple, as shown below.

Java implementation

The RandomPicker class takes as argument for its constructor a list/an array of objects of the generic type T. Afterwards, it can be used to randomly pick one element from the list using the pick method. It uses the Random class included in the java.util package to generate a pseudorandom index of the list, which represents the index of the item in the list that is picked.

Here is the RandomPicker class:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RandomPicker<T> {
    
    private List<T> list;
    private Random r;
    
    public RandomPicker(List<T> list){
        this.list = list;
        r = new Random();
    }
    
    public RandomPicker(T[] list){
        this.list = new ArrayList<>();
        for (int i = 0; i < list.length; i++){
            this.list.add(list[i]);
        }
        r = new Random();
    }
    
    public void setList(List<T> list){
        this.list = list;
    }
    
    public void setList(T[] list){
        this.list = new ArrayList<>();
        for (int i = 0; i < list.length; i++){
            this.list.add(list[i]);
        }
    }
    
    public T pick(){
        return list.get(r.nextInt(list.size()));
    }
}

Here is an example of how it is used:

String[] list = {"a","b","c","d","e"};
RandomPicker<String> rp = new RandomPicker<>(list);
System.out.println(rp.pick());

You can try running the above example multiple times to see that the element picked is not always the same.

Conclusion

The RandomPicker class can be easily translated to other programming languages. It is not common to be in need of such a class, but it might be useful to someone.

That's all. Let me know of any questions.

No comments:

Post a Comment