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
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.
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.
* 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 ]
Joined: Apr 18, 2006
I'll give these a try and let you know what happened.
subject: Finding a Specific Object in an ArrayList