| Author |
How to check whether a number is in Arraylist or not ?
|
nirjari patel
Ranch Hand
Joined: Apr 23, 2009
Posts: 238
|
|
I have created a list object List [] numbers = new ArrayList[5]
I am generating a random integer number as
num6 = (int)(Math.random()*10)
Now, I want to add a new sixth element to the existing List.
I can do that using numbers.add(6).
I want to check that this value num6 is not already included in existing values in the list numbers[].
How can I compare the generated value of num6 with existing values in numbers[] ?
Thanks
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16690
|
|
nirjari patel wrote:
Now, I want to add a new sixth element to the existing List.
I can do that using numbers.add(6).
Actually, no. The numbers variable is a List array reference, and not a List reference -- references to arrays don't have an add() method.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Tom Reilly
Rancher
Joined: Jun 01, 2010
Posts: 618
|
|
EDIT: I posted this the same time Henry posted his response so it is mostly reduntant.
In answer to your specific question, you have to loop through the list looking for the number.
As for your posted code, you didn't create a "list object". You created an array of List references called numbers. That is, you created 5 list objects. So if you tried numbers.add(6) you would get a compiler error because numbers is an array and an array does not have an add() method.
|
 |
 |
|
|
subject: How to check whether a number is in Arraylist or not ?
|
|
|