• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Finding a Specific Object in an ArrayList

 
Bob Harrison
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't quite get my head around this.

I have a userVO object that has a field, messages that is an ArrayList (Messages) of message objects (MessagesVO) that have a messageID (integer) field. Is there a way that I can extract a specific message by it's messageID?

I've tried code such as:
int index = userVO.getMessages().indexOf(messagesVO.messageID);
messagesVO = (MessagesVO)userVO.getMessages().get(index);

but this doesn't work. Can someone point me in the right direction or tell me that it can't be done??

Thanks,

Bob
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use a HashMap()
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could indeed put the objects in a HashMap, using the id as the key. Another option is to write a method whose job it is to find one object by id; inside that method, put a "for" loop which examines each object in the list, in turn, and returns the one with the right id, or null if isn't found.
 
Ryan McGuire
Ranch Hand
Posts: 1055
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Orrrrrrr....

You could override Object.equals() in your MessagesVO class so that it returns true iff the messageID values for the two messages are the same. *

Pro:
- ArrayList already uses equals() to check for inclusion.

Cons:
- You should also override hashcode(), so that it relies on nothing but messageID. This will keep your class consistent, even if you use MessageVO objects as keys in a HashMap.
- You'll have to instantiate a new MessageVO object with a given messageId just to see if a message with that ID already exists in the ArrayList. But it looks like you already did that in your sample code.



Then...


* I just reread items 7 and 8 on overriding equals() and hashcode() in Joshua Bloch's "Effective Java". Now that I have that hammer, every question looks like a nail.
[ June 06, 2006: Message edited by: Ryan McGuire ]
 
Bob Harrison
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.

I'll give these a try and let you know what happened.

Cheers,

Bob
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic