Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to check whether a number is in Arraylist or not ?

 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21514
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic