除了使用哈希表还有其他选择吗? 我有这段代码,想知道我是否可以在不使用它的情况下做到这一点。我所拥有的正在寻找工作,但有人告诉我不要使用它。感谢您的帮助。
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;
}
}
最佳答案
Hashtable
是同步的,这可能会导致性能问题,这就是为什么建议您使用类似 HashMap
或任何其他实现 Map 的合适类的原因
。
实际上,如果您将代码更改为使用 Map
,您将不会遇到重大问题(实际上 Hashmap
本身实现了 Map
)。
关于java - 哈希表替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17915560/