Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

[JAVA] Scattering ArrayList contents?

Hello!

Say I have:

ArrayList<String> example = new ArrayList<String>();

example.add("Hello");

example.add("World");

example.add("How");

example.add("Are");

example.add("You");

What is the best method to completely randomize this?

Is there a specific method I missed or maybe a package ready-for-use?

Thanks!

Update:

I came up with a pretty interesting method that IDK if it works.

public void shuffle(){

int deck_length = cards.size(); // how big the deck is

int cur_num = 0;

ArrayList used_numbers = new ArrayList ();

ArrayList new_arrl = new ArrayList ();

do {

Random ran = new Random();

cur_num = ran.nextInt(deck_length);

} while(used_numbers.contains(cur_num));

used_numbers.add(cur_num);

for (int i=0; i

1 Answer

Relevance
  • 7 years ago
    Favorite Answer

    use java.util.Collections.shuffle

    import java.util.*;

    public class CollectionsDemo {

    public static void main(String args[]) {

    // create array list object

    List arrlist = new ArrayList();

    // populate the list

    arrlist.add("A");

    arrlist.add("B");

    arrlist.add("C");

    System.out.println("Initial collection: "+arrlist);

    // shuffle the list

    Collections.shuffle(arrlist);

    System.out.println("Final collection after shuffle: "+arrlist);

    }

    }

Still have questions? Get your answers by asking now.