This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Java in General and the fly likes Finding a Specific Object in an ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Finding a Specific Object in an ArrayList" Watch "Finding a Specific Object in an ArrayList" New topic

Finding a Specific Object in an ArrayList

Bob Harrison

Joined: Apr 18, 2006
Posts: 12
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??



"In theory there is no difference between theory and practice. In practice there is."<br />Yogi Berra
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
use a HashMap()
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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.

[Jess in Action][AskingGoodQuestions]
Ryan McGuire
Ranch Hand

Joined: Feb 18, 2005
Posts: 1046

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. *

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

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


* 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

Joined: Apr 18, 2006
Posts: 12

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


I agree. Here's the link:
subject: Finding a Specific Object in an ArrayList
It's not a secret anymore!