check element exists in a list collection

Posted on 2005-05-10
Last Modified: 2012-05-05
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.

Question by:ericworldz
    LVL 92

    Accepted Solution

    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.
    LVL 15

    Assisted Solution

    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)

    Featured Post

    Threat Intelligence Starter Resources

    Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

    Join & Write a Comment

    Suggested Solutions

    For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
    Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
    Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
    This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

    754 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now