Reputation: 51
Are there any alternatives to using hash tables? I have this code and was wondering if I could make do without using it. What I have is working find, but I've been told not to use it by some people. Any help is appreciated.
import java.util.Hashtable;
import java.util.Enumeration;
public class Cart
{
public Hashtable items = new Hashtable();
public Enumeration getEnumeration()
{
return items.elements();
}
public void addItem(String itemId,String desc, float price, int quantity)
{
String[] item = {itemId, desc, Float.toString(price),
Integer.toString(quantity)};
if (items.containsKey(itemId))
{
String[] tmpItem = (String[])items.get(itemId);
int tmpQuant = Integer.parseInt(tmpItem[3]);
quantity += tmpQuant;
tmpItem[3] = Integer.toString(quantity);
}
else {
items.put(itemId, item);
}
}
public float getTotalCost() {
Enumeration e = items.elements();
String[] tmpItem;
float totalCost = 0.00f;
while (e.hasMoreElements()) {
tmpItem = (String[])e.nextElement();
totalCost += (Integer.parseInt(tmpItem[3]) *
Float.parseFloat(tmpItem[2]));
}
return totalCost;
}
}
Upvotes: 1
Views: 2599
Reputation: 604
if you want to find an item with the itemId
the best data structure would be HashMap
because of access time.
but if you items are sorted according to the itemId
, you can use other data structures as arraylist
or array
or even making your own class with four public variables.
but i say once a gain for searching the best DS would be hashMap
Upvotes: 1
Reputation: 17422
Hashtable
is synchronized and that could cause performance issues, that's why you're advised to use something like a HashMap
or any other suitable class that implements Map
.
Actually, if you changed your code to use a Map
you wouldn't have mayor problems (actually Hashmap
itself implements Map
).
Upvotes: 2