我正在尝试创建一个方法来计算 Flower 对象的数量(顺便说一句,创建了一个名为 flower 的类),该方法返回对象 flower 数组中特定花朵的数量。
我正在使用 HashMap 将一个整数(总和)映射到一个键(键是花对象)。但是,当我输出数组时,堆中键的内存地址与键在 HashMap 表中的位置一起。
然而,我的意图是打印 flower(主要是它的名称)以及该数组中属于相同 Flower 对象类型的花的数量。
我的代码如下:
private void displayFlowers(Flower flowerPack[]) {
// TODO: Display only the unique flowers along with a count of any
// duplicates
/*
* For example it should say Roses - 7 Daffodils - 3 Violets - 5
*/
HashMap<Flower, Integer> flowerFrequency = new HashMap<Flower, Integer>();
for (Flower aFlower : flowerPack) {
if (flowerFrequency.containsKey(aFlower)) {
Integer i = flowerFrequency.get(aFlower);
i++;
} else {
flowerFrequency.put(aFlower, new Integer(1));
}
}
System.out.println(flowerFrequency);
}
输出是这样的:
1: Add an item to the pack.
2: Remove an item from the pack.
3: Search for a flower.
4: Display the flowers in the pack.
0: Exit the flower pack interfact.
4
{null=1, Flower@6bc7c054=1, Flower@42a57993=1, Flower@75b84c92=1}
按照指示,我还向 Flower 类添加了 toString() 和 equals() 方法,如下所示:
我在 Flower 类中添加了 toString() 和 equals() 方法,如下所示:
public String toString() {
return this.color + " " + this.name + " smells like " + this.scentType + " is Thorny " + this.hasThorns;
}
@Override
public boolean equals(Object otherFlower) {
if (otherFlower == null) {
return false;
}
if (!Flower.class.isAssignableFrom(otherFlower.getClass())) {
return false;
}
final Flower other = (Flower) otherFlower;
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
if (!(this.color.equals(other.color))) {
return false;
}
if (!(this.scentType.equals(other.scentType))) {
return false;
}
if (this.hasThorns != other.hasThorns) {
return false;
}
return true;
}
最佳答案
除了覆盖 toString()返回你想要读取的字符串,你的代码包含一个真正的错误:
if (flowerFrequency.containsKey(aFlower)) {
Integer i = flowerFrequency.get(aFlower);
i++;
不会工作。你看,Integer 对象是不可变的。您的代码从 map 中获取计数器,将它变成一个 int(上面的代码甚至可以编译吗?!)......然后忘记它!您不能修改存储在该映射中的 Integer 的值,相反,您必须将一个更新的值放回映射中:
if (flowerFrequency.containsKey(aFlower)) {
Integer currentCounter = flowerFrequency.get(aFlower);
flowerFrequency.put(aFlower, currentCounter+1);
编辑:当然,为了使该 Map 真正适用于您的花卉对象,您必须为 equals()/hashCode() 提供有意义的覆盖(有关一些指导,请参阅 here)。
关于java - 计算 "Flower Objects"数组中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40332944/