0

I have to store a product and its corresponding price. Which of the below methods would be better:

Method 1:

public class Product { String productName; Integer productCost; } 

Method 2:

Map<String, Integer> product. 

I assumed that using Map make things easier but still I was suggested to use value Object.

Is there any advantage of using Method 1 over Method 2 in terms of memory and performance? In what situation we can use these two methods?

7
  • The advantage is encapsulation. Commented Sep 9, 2013 at 15:27
  • 2
    You mean apart from type safety, compiler checks for typos, code-as-documentation and a reduced number of co-developers who claw their eyes out? No, almost no other benefits. Commented Sep 9, 2013 at 15:28
  • How big of collection will you need to store? 10, 100, 1000 items? Commented Sep 9, 2013 at 15:31
  • Thank you. So it is better to use value object. Then in what case i can use Map. Commented Sep 9, 2013 at 15:32
  • @Gita: my (now deleted) answer assumed a slightly different use of the HashMap, which is much worse than what you describe here. Feel free to ignore it ;-) Commented Sep 9, 2013 at 15:34

2 Answers 2

1

You should consider using a Map if you need to quickly look up the price of an item based on its name. The difference here is that this lookup operation would be O(n) if you choose the first method and O(1) if you choose the second (since with the first you have to go through your entire collection of Products to find the one with the right name).

If you don't have too many products you want to store (e.g. ~10, as you mentioned), then the performance difference will probably be negligible, and you might be better off choosing whichever approach is easier to understand/manage. As the number of products you want to store increases substantially, then the difference can become more apparent.

Of course, if you don't need this quick look up feature then it doesn't make much sense to use a Map at all.

Sign up to request clarification or add additional context in comments.

Comments

1

The value in the Object is recommended way when you want to keep the software quality high. With the Map you should "carry" it whenever you need to use the value of the Object and consequently you create a lot of copies of it. Getting the value from a Map has an impact on performace as well and you have moreover to save all the Objects created in it, preventing the garbage collector to sweap them when no more needed.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.