1

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..?

2 Answers 2

4

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Don't write ... == false, write ! .... For booleans == and != are only sensible if both sides are not constant.
Thanks for noticing it, Paulo! Edited!
3

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);

1 Comment

In fact, the contains method compares each element, until a fitting one is found. (It used the equals method instead of ==, too.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.