0

I want to add some values in arraylist but at random index. Is this possible?

2 Answers 2

2

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)));
}
Sign up to request clarification or add additional context in comments.

3 Comments

if Math.Random class sends same number again, then what would be the solution
The maximun size of the arraylist is 4 and i want to have the random values from 1 to 4(int only). But random produces decimal numbers isn't it?
Calculate it again? That is, list.get(randomIndex) != null ? get another index : use that index .
0

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

3 Comments

If you don't want to add at same position again, you can store the positions into a separate ArrayList and can add a while loop which continues to generate random positions until a unique value is found.
This doesnt work beacuse the original ArrayList is prodyced with size=0
then you can use arrayList.size()+1 instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.