check element exists in a list collection

how to check if an element exists in a list?

i have a private instance var : private List account;

// the list start with an index of 0, -1 to prevent IndexOutOfBoundsException
         int _accountNumber = accountNumber - 1;
         Account _account = (Account) account.get(_accountNumber);

how to check that _accountNumber does exist in the account list? if not i want to throw an exception error.

thanks!
ericworldzAsked:
Who is Participating?
 
objectsConnect With a Mentor Commented:
Use the contains() method to check if an element exists
But it looks like you want to know whether an element exists at a given index, if so you can check if returned _account is null.
0
 
aozarovConnect With a Mentor Commented:
If you are accessing List by index (as you do in your example) then prefer using ArrayList (or any List that implements the RandomAccess) otherwise
you might travers N elements to get the item in the Nth position. Also make sure that your index is not >= list.size() and is >= 0
If you want to use the contains() then prefer HashSet (if order is not important and there are no duplicates) or LinkedHashSet if you want to maintain order when
iterating and don't have duplicates (or willing to ignore them)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.