• Post Reply Bookmark Topic Watch Topic
  • New Topic

Retrieve empl from an arraylist

 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

Say I have an arraylist with 1,000 items (Employee � id, name, address)
I would like to find the Employee with ID=755?
What�s the best way to do that?
Currently I�m doing this:



is there a better way to do this? HashMap is not an option.
 
erdem ozdemir
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If ids in your list elements are in order, you can use binary search algorithm to find the
employee.

Here is an algorithm of how you can do this:

http://en.wikipedia.org/wiki/Binary_search


But insertion and deletion of employees are not much efficient in this case.

Btw, if insertions and deletions are used many times, you can use a heap (data structure), but implementing heap with arraylist might be hard.

I hope, these information is useful for you.
[ June 16, 2006: Message edited by: erdem ozdemir ]
 
steve souza
Ranch Hand
Posts: 862
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure why you can't use a hashmap. That is the best way to do random access via a key. You can always conver to an ArrayList if you need to. Another option is to store it both ways. Not sure why you are hardcoding 755 too.

Also this isn't really a performance question.
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If your IDs are unique and in sequence, and rarely removed, you could use the id as index, and retrieve the data by
 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for your comments

If I use hashMap and 'convert' it back to arraylist - how efficent is that?
also, the

Empl empl = arraylist.get (id);

is not a good idea as they are not in sequence.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!