[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

check element exists in a list collection

Posted on 2005-05-10
4
Medium Priority
?
775 Views
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.

thanks!
0
Comment
Question by:ericworldz
2 Comments
 
LVL 92

Accepted Solution

by:
objects earned 100 total points
ID: 13974697
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
 
LVL 15

Assisted Solution

by:aozarov
aozarov earned 100 total points
ID: 13974770
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

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
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.
Suggested Courses
Course of the Month18 days, 2 hours left to enroll

830 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