| Author |
Which collection?
|
Kudret Serin
Ranch Hand
Joined: Aug 02, 2005
Posts: 165
|
|
Hi all, I am learning collections and trying to implement a simple application. I have 20 different String objects and i want to select one of them randomly when i click a button. None of them should be selected twice. Which collection class is the best? How should i construct the programlogic? Thanks in advance for any suggestions. Cheers
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
There are lots of ways you could do this, including a clever algorithm using a simple array. But if you're using Collections, you might consider the trade off between fast lookup (for selecting elements) and fast deletions from the middle (if you decide to remove elements as they're selected). What ideas have you considered so far?
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
Julien Grenier
Ranch Hand
Joined: Sep 01, 2005
Posts: 41
|
|
hi, You could put all your String in an ArrayList and use the Collections.shuffle() method. This will shuffle the elements randomly in your list.
|
 |
Kudret Serin
Ranch Hand
Joined: Aug 02, 2005
Posts: 165
|
|
i thought so: generate a number with Math.random() and use map to store strings with numbers. get the string with corresponding number. But i don't want to get the same string again when random() the same number returns. putting it in a loop until it returns a different number? How can i check it? Arraylist and Collections.shuffle() sounds good but does it solve the repetition problem? thanks alot again for the answers Cheers
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
|
Once the elements are randomly shuffled, you don't need to make random selections. Just move through the list sequentially.
|
 |
 |
|
|
subject: Which collection?
|
|
|