Results 1 to 4 of 4
- 04-13-2011, 06:10 AM #1
Member
- Join Date
- Mar 2011
- Posts
- 20
- Rep Power
- 0
extracting 5 random elements from an ArrayList
i have an arraylist of 30 elements. i need to randomly extract any 5 elements from the list. i am using the Random function but i am not getting 5 different elements, the elements are getting repeated. how to get unique entries from the arraylist? please help :(
- 04-13-2011, 06:13 AM #2
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
Use a random object and use nextInt for the range 0-29, use that to index into the array list, then keep track if numbers previously generated and ignore the random number if it's been seen already.
- 04-13-2011, 06:15 AM #3
If allowed the simplest way is to use Collections.shuffle and poll the first 5 objects.
- 04-13-2011, 06:17 AM #4
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,561
- Rep Power
- 11
Or shuffle() the list and take the first 5 elements. (But note the shuffle is "in place" - ie it will alter the ordering of the list being shuffled - so you might want to copy the list first.)
Similar Threads
-
Extracting values from textfile with semi-random content
By Kenjitsuka in forum New To JavaReplies: 9Last Post: 03-02-2011, 11:52 PM -
Adding elements to an ArrayList
By ArcherSam in forum Advanced JavaReplies: 7Last Post: 01-28-2011, 03:05 PM -
Fill array with random number, but elements cannot be duplicated
By John_shok in forum New To JavaReplies: 6Last Post: 10-03-2010, 08:25 AM -
Cannot swap elements in ArrayList
By glchau in forum New To JavaReplies: 4Last Post: 05-30-2010, 08:03 AM -
Help printing specific ArrayList elements
By CirKuT in forum New To JavaReplies: 5Last Post: 02-03-2009, 12:24 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks