オブジェクト花の特定の花の数を返すFlowerオブジェクト(flower btwというクラスを作成した)の数を数えるメソッドを作成しようとしています。アレイ。"Flower Objects"の配列内での出現回数のカウント
私はキー(花オブジェクトであるキー)に整数(合計量)をマッピングするために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);
}
出力は次のようである:指示されたように、私ものtoString()とequals()花のクラスにメソッドを追加した
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}
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 ...に置き、コンパイラが**エラー**を表示します。それはequals(Object other)でなければなりません!ちょうど**リンク**に従ってください私は私の答えを入れました! – GhostCat
ありがとう、私が作った編集を保存するのを忘れました、あなたの考えを今共有してください。ありがとう! – Linuxn00b