user1816464
user1816464

Reputation: 223

Java ArrayList multiplication

Hello all I have the following line of code

solution first = mylist.remove((int)(Math.random() * mylist));

Which give me an error stating

The operator * is undefined for the argument type(s) double, ArrayList<solution>

I am trying to remove a random number in my arrayList from my ArrayList

Any help would be appriciated.

Upvotes: 0

Views: 993

Answers (2)

Boris the Spider
Boris the Spider

Reputation: 61128

You need to find a random number in within the range of your list size

final Random random = new Random();

mylist.remove(random.nextInt(myList.size()));

Make sure you create a Random and store it as otherwise it may create the same number repeatedly (it is only pseudorandom).

Also, the nextInt method excludes the top limit so mylist.size() will not return an invalid index.

Upvotes: 0

rgettman
rgettman

Reputation: 178253

It looks like you are attempting to remove a random element from your list. To cover all elements with your random index, you need the list size.

It doesn't make sense to multiply a number by an ArrayList. You can't get the size of your list by directly specifying just your list in your code. Call the size() method on your list. That returns an int that can be multiplied.

Upvotes: 4

Related Questions