my dog learned polymorphism*
The moose likes Beginning Java and the fly likes How to check whether a number is in Arraylist or not ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to check whether a number is in Arraylist or not ?" Watch "How to check whether a number is in Arraylist or not ?" New topic
Author

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

nirjari patel
Ranch Hand

Joined: Apr 23, 2009
Posts: 371
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: 18545
    
  40

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to check whether a number is in Arraylist or not ?
 
Similar Threads
Standard Deviation
read a comma seperated file into an arraylist
Comparing Objects containing List
What am I missing here? (ArrayList check)
Extra Elements on ArrayList