Saturday, March 14, 2009

Shuffling lists and arrays

My task is to add some elements to a list, shuffle it, and then generate a sublist.

The Collections Interface includes methods which can be used on all the subtypes of collection. Then each type of collection has some additional methods, specific to that type. Looking down the interface, I could use the add method to add elements one by one, the addall to add all the elements of another collection. The array operations include toArray, which presumably means putting elements in an array not taking them from it.

The Set Interface on first glance looks very similar to the generic one.

The List Interface has the sublist method but as with the others, the group add feature seems to require you to add from another collection. So how do you populate the first collection? The answer is given halfway down the page, and I'll quote from the page because there is nothing to be gained by paraphrasing:

"The Arrays class has a static factory method called asList, which allows an array to be viewed as a List. This method does not copy the array. Changes in the List write through to the array and vice versa."

This is very handy. Effectively it enables one to manipulate an array like a list collection. I applied it as follows:

import java.util.*;

public class jShuffle2 {
public static void main(String[] args) {
String[] items = {"1 + 5","5 + 2","1 + 1","2 + 5"};
List list = Arrays.asList(items);
Collections.shuffle(list);
System.out.println(list);
System.out.println("First item: " + items[0]);
}
}


I cheated a bit here because I borrowed code from the card shuffling class, which is fine as a demo of technique, but I will need to do more work because my app needs numbers as well as strings.

No comments: