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);
            }
          }
3

1 Answer 1

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

4
  • how to create an array with the data System.out.println("cf:"+di); Apr 24, 2012 at 10:07
  • I have edited my answer to create an array...
    – Sridhar G
    Apr 24, 2012 at 10:25
  • Oh! it works... thanks. I only replace the code of shufle to output: I want the new array to be sorted by random Apr 24, 2012 at 12:31
  • Nice to hear that! If you find this answer was correct then you can accept the answer.
    – Sridhar G
    Apr 24, 2012 at 12:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.