• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 259
  • Last Modified:

Searching An ArrayList in Java

Hello there,

I was wondering if someone could help me with something to do with searching ArrayLists.

I have an arraylist called wrkStnNames, which contains a number of computer names.  I am now in the process of creating a constructor of the class wrkStn which allows one string to be passed to it ,

This constructor has an if statement which checks to see if the string being passed to that constructor matches the string in the array list.  If so it will continue and update that array list .. if not it ends.

I am having problems working out how to search the arraylist for the presence of the string passed to the constructor ... any ideas how I could do this ?


- J
  • 3
  • 2
1 Solution
neonlinesProject managerCommented:

ArrayList list = new ArrayList(); //ur ArrayList Object
int pos = Collections.binarySearch(list, "constructor parameter"); // list must be sorted first

if pos is -1, the given string is not in the Arraylist
Jase_xAuthor Commented:
Thanks mate, that will work a treat !
if you call

boolean present = arrayList.contains(name);

it won't alter the current order of the List
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

>>if pos is -1, the given string is not in the Arraylist

That's not actually how binarySearch works - see api docs
neonlinesProject managerCommented:
>>That's not actually how binarySearch works - see api docs

The following statements taken from api

index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size(), if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

-- Returns the current index or a negative number of the insertion point
Exactly ;-)
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.

Join & Write a Comment

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.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now