stratis
stratis

Reputation: 8052

checking an entire ArrayList in Java

I have a simple idea on my mind but I am not sure how to implement it properly... Here's the deal:

Say there is an ArrayList called myList of size 5 and then there is an Integer called testNumber. The values inside myList and/or testNumber are irrelevant.

What I need to do is compare the testNumber variable with each of myList's integers and if testNumber doesn't equal to none of them, then perform an operation (i.e. System.out.println("hi");).

How should I go about it..?

Upvotes: 1

Views: 167

Answers (2)

Amokrane Chentir
Amokrane Chentir

Reputation: 30405

ArrayList has a method called contains() which is suitable for this task:

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

You can use it as follow:

if(!myList.contains(testNumber)) {
   PerformOperation();
}

Upvotes: 4

aioobe
aioobe

Reputation: 421310

You simply do

if (!myList.contains(testNumber))
    System.out.println("no element equals " + testNumber);

Strictly speaking this probably doesn't "compare each element to testNumber". So, if you're actually interested in the "manual" way of comparing each element, here's how:

boolean found = false;
for (int i : myList) {
    if (i == testNumber)
        found = true;
}

if (!found)
    System.out.println("no element equals " + testNumber);

Upvotes: 3

Related Questions