I want to add some values in arraylist but at random index. Is this possible?
2 Answers
You could use Math.Random with a range to do this. I doubt you want to be adding it at ANY index because ArrayList is a dynamically expanding array which means that it will have to resize if you use indexes beyond a certain size. This will make your inserts more costly than they need to be and it will also take up more memory than needed. If you know you'll have only say.. 100 items then just pick a random value between 1 - 100.
EDIT: Random doesn't produce decimal values if you do the following.. you say you want a range between 1-4 than the following should give you what you want...
public int Rand(){
return ((int)(1+(Math.random()*4)));
}
3 Comments
list.get(randomIndex) != null ? get another index : use that index .Yes it's possible, Math.random() can be used with overloaded add() method of ArrayList.
For example:
arrayList.add(getRandomIndex(arrayList.size()),object);
And the getRandomIndex() method can be like:
public int getRandomIndex(int size){
return ((int)Math.random()*size)
}