This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Which collection? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Which collection?" Watch "Which collection?" New topic
Author

Which collection?

Kudret Serin
Ranch Hand

Joined: Aug 02, 2005
Posts: 167

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: 167

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Which collection?
 
Similar Threads
Mughal's Mock Exam-Collections (java.util.packages)
List or Set??
To extend or not to extend AbstractCollection
findXXX methods in EJB 2.x
Unchecked cast warning