[英]Removing object element from HashSet
我正在开发钱包并从基础开始。 我将 Penny 对象添加到存储钱的 HashSet 中。 我将容量初始化为 5 并从一个完整的钱包开始。
尝试花费一分钱时,返回 null(如预期的那样),但是当调用 moneyCheck() 方法时,仍然有 5 个硬币。
我不确定该怎么做,因为我正在尝试使用 .remove() 方法删除 Penny,并且 object 没有从 HashSet 中删除。
任何方向将不胜感激。 谢谢
import java.util.HashSet;
public class Wallet{
private HashSet<Penny> walletPenny;
public Wallet(){
int walletCapacity = 5;
walletPenny = new HashSet<>();
int counter = 0;
while (counter < pocketCapacity){
pocketPenny.add(new Penny());
counter++;
}
}
public Penny removePenny(){
Penny spentPenny = null;
if (walletPenny.isEmpty()){
System.out.print("No more pennies!\n");
return spentPenny;
}
else {
pocketPenny.remove(spentPenny);
System.out.println(("Spent penny!"));
}
return spentPenny;
}
}
public int moneyCheck(){
System.out.print("Money remaining: " + walletPenny.size() + "\n");
return walletPenny.size();
}
找到了答案,并认为我会更新这个,以防其他人有同样的问题。
为了移除一分钱,我用迭代器初始化了一个 Penny object,以在 HashSet 中找到下一个可用的 object。 然后我返回该值以在程序的其他地方使用。
public Penny removePenny(){
Penny spentPenny;
if (walletPenny.isEmpty()){
System.out.print("No more pennies!\n");
spentPenny = null;
return spentPenny;
}
else {
spentPenny = walletPenny.iterator().next();
walletPenny.remove(spentPenny);
System.out.println(("Spent penny!"));
return spentPenny;
}
}
当您尝试使用pocketPenny.remove(spentPenny)
删除便士时,Java 会尝试查找要删除的便士。 为了做到这一点,它使用equals
并迭代HashSet
直到找到一个与您的花费的便士相等(身份明智)的spentPenny
。 更多关于remove()
的工作原理。 由于您将 null 提供为spentPenny
,因此它将不匹配任何内容(您的 5 便士已初始化,因此它们不为空)。 如果您检查.remove()
方法的返回值,您可以验证这一点——它将是false
。
为了解决这个问题,您需要:
remove()
方法时提供非空值Penny
class 中实施equals()
完整示例:
public class Penny {
private final int serialNum;
public Penny(int serialNum) {
this.serialNum = serialNum;
}
@Override
public int hashCode() {
int hash = 5;
hash = 79 * hash + this.serialNum;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Penny other = (Penny) obj;
return this.serialNum == other.serialNum;
}
}
然后创建你的便士:
int counter = 0;
while (counter < pocketCapacity){
pocketPenny.add(new Penny(counter));
counter++;
}
现在你有 5 个便士,编号从 0 到 4。你可以删除一个,例如 #3:
Penny spentPenny = new Penny(3);
pocketPenny.remove(spentPenny);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.