我正在尝试创建一个方法来计算Flower对象的数量(创建一个名为“花btw”的类),该对象返回对象花中特定花朵的数量阵列。计算“花对象”数组中的出现次数
我使用HashMap为了将一个整数(总和)映射到一个键(键是花对象)。但是,当我输出数组时,密钥在堆中的内存地址与HashMap表中键的位置一致。
然而,我的意图是打印花朵(它的名字主要是),该花朵的数量与花朵对象类型相同。
我的代码如下:
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, [email protected]=1, [email protected]=1, [email protected]=1}
按照指示,我也加入了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;
}
把你的等于@Override ...,你会注意到,编译器给你一个**错误**。它必须是equals(Object other)!只需按照**链接**我把我的答案! – GhostCat
谢谢,我忘了保存我所做的修改,请现在分享您的想法。谢谢! – Linuxn00b