我正在开发一个钱包,并且已经从基础知识开始。我正在将Penny对象添加到存储钱的HashSet中。我将容量初始化为5,然后从满钱包开始。
当尝试花费一便士时,会返回null(如预期(,但当调用moneyCheck((方法时,仍然有5个硬币。
我不知道该怎么办,因为我正试图使用.remove((方法删除Penny,而该对象并没有从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,我用迭代器初始化了一个penny对象,以在HashSet中找到下一个可用的对象。然后我返回该值,以便在程序的其他地方使用。
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便士已初始化,因此它们不是null(。如果您检查.remove()
方法的返回值,您可以验证这一点——它将是false
。
为了解决这个问题,你需要:
- 在调用
remove()
方法时提供一个非null值 - 在
Penny
类中隐含equals()
- 跟踪您创建的Pennies,以便以后可以删除它们
完整示例:
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);