TranceAddict Forums

TranceAddict Forums (www.tranceaddict.com/forums)
- Chill Out Room
-- Java Programming Question...need some help


Posted by Vaedyn on Jan-04-2005 21:00:

Java Programming Question...need some help

Alright programming gurus...I am in need of some help. Here is the current situation.

If I have a Collection of Products and I want to test if the collection contains a given product using ProductID to look it up, how should I handle it?

Assuming Product.equals() tests for the equality of the Product.productID property, I could create a temporary Product object with the right ProductID and say:

Product testProduct = new Product();
testProduct.setProductID(new ProductID(targetProductID));

if( collection.contains( testProduct ) )
{
// found it....
}

But that seems wasteful. I'd really like to be able to do:

if( collection.contains( targetProductID ) )

But that requires the Product object to consider ProductID objects to be equivalent as long as the ID matches, which seems to break the semantics of equals().

I could build a HashMap from the Collection, keyed by ProductID, but that's a lot of work if I only want to perform one test.


How should I handle this?

I was leaning more towards the HashMap. Let me know what you all think.


Thanks in advance and sorry for the long post

Vaedyn


Posted by cviper on Jan-05-2005 00:42:

If you are doing a single test (as you mentioned in your post), I'd go for the equals method.

In equals() you can could test if the Object passed to it is of type Product or ProductID:

// Somewhere in you Product class
public boolean equals(Object obj)
{
if( obj.getClass() == ProductID.class )
{ compare with the ProductID }
else if( obj.getClass() == Product.class )
{ compare the "whole" Product Object, using getHash() or something }
else return false;
}

That way you should not break anything else You probably also need to overload the equals method for the ProductID class...

If you're going to compare more than a few objects, a HashMap probably would speed up things.


Posted by Operation-Green on Jan-05-2005 00:58:

Just out of curosity is this for the web or a program?
I dont know much about Java but what I do know is I hate working with it, I orginally did my website in mostly java, and it dint work with a lot of browsers.


Posted by smokeape on Jan-05-2005 01:03:

Sorry, Visual Basic dude here with database programming. I can follow the programming logic you listed to a degree, but cannot give you any advice worth a damn. Step in my world and I'm an absolute pro though.


[[[smoke]]]

Morgan Page & Gregory Shiff ft Astrid Suryanto - All I Know (Cattaneo & Garcia Mix)


Posted by Vaedyn on Jan-06-2005 04:10:

Thanks all. I went the HashMap route.


Thanks Again,

Vaedyn



Powered by: vBulletin
Copyright © 2000-2021, Jelsoft Enterprises Ltd.