开发者

problem with random number generation

ArrayList <String> fil = new ArrayList<String>(); 
ArrayList <String> lif = new ArrayList<String>();

int x=0;
long tim = System.currentTimeMillis(); 
Random random = new Random(tim); 
for(int i=0;i<fil.size();i++)
{
 x =random.nextInt(fil.size());
         for(int y=0;y<lif.size();y++)
         {
             if(fil.get(x).equals(lif.get(y)))
             {
                 i--;
                 continue;
             }
         }
         System.out.println("Set the value of x"+x);
          lif.add(i, fil.get(x));//array index out of bound exception


     }

I'm t开发者_如何学JAVArying to copy the contents of ArrayList fil to lif in a different order, but I get an ArrayIndexOutOfBoundException in the commented line. I'm using a nested for-loop to check if the elements of new ArrayList are unique.


Why don't you try Collections.copy and Collections.shuffle methods.


Isn't Collections.shuffle a better alternative?


The "lif"-ArrayList must be preallocated to hold "fil.size()" elements before reshuffeling the contents. Try adding "fil.size()" null elements before entering you're for loop.

Note! This is a very uneffective approach to do reshuffeling, see Collections.reshuffle() for a better approach.


if(fil.get(x).equals(lif.get(y)))
{
    i--;
    continue;
}

One possible problem is if 'i' is 0 (zero). The decrement i-- will set 'i' to -1 which will cause an exception with...lif.add(i, fil.get(x));

That may not be the answer but you should be checking that i, x and y are all within the bounds of the ArrayList objects.


Modify commented line to:

lif.add(fil.get(x));

This should fix exception. However, your algorithm doesn't look very good.


Change the code to this and check if that works

x =random.nextInt(fil.size() - 1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜