0

Possible Duplicate:
How do I randomly fill an array in Java?

The last line of code below prints numbers in order. How to create an array where value are sorted randomly?

          List<Users> u = new ArrayList<Users>();
          u.add(new Users(1, 5));
          u.add(new Users(2, 4));
          u.add(new Users(3, 8));

          for (Users us1 : u)
          {
            int si1 = us1.getCf();
            int di = us1.getId();
            for (int j = 0; j < si1; j++)
            {
              System.out.println("cf:" + di);
            }
          }
Community
  • 1
  • 1
  • Create a permutation of the indexes using Random and then load the values into the final array using that to set the order. – duffymo Apr 24 '12 at 09:54
  • http://stackoverflow.com/questions/375351/most-efficient-way-to-randomly-sort-shuffle-a-list-of-integers-in-c-sharp – Bitmap Apr 24 '12 at 09:56
  • possiblity of duplicate : http://stackoverflow.com/q/2496774/668970 – developer Apr 24 '12 at 09:56

1 Answers1

3

Just use,

Collections.shuffle(yourList)

As per your requirement I made some changes in your code,

List<Users> u = new ArrayList<Users>();  
u.add(new Users(1, 5));  
u.add(new Users(2, 4));  
u.add(new Users(3, 8));  
Collections.shuffle(u);  

List<Integer> output = new ArrayList<Integer>();  
for (Users us1 : u) {  
    int si1 = us1.i;  
    int di = us1.i;  
    for (int j = 0; j < si1; j++) {  
        System.out.println("cf:" + di);  
        output.add(di);  
    }  
}  

Integer[] result = output.toArray(new Integer[output.size()]);

Hope it helps :)

Sridhar G
  • 808
  • 5
  • 14