gpt4 book ai didi

java - 添加元素以设置的方法总是抛出自定义异常

转载 作者:行者123 更新时间:2023-11-30 11:26:55 25 4
gpt4 key购买 nike

好的,所以我有一个方法可以将元素添加到列表中,但它总是抛出我的自定义异常,无论如何,即使我创建的 Set 中没有元素。

private Set<Plan> planSet = new HashSet<Plan>();
public Plan createPlan(String name) throws DuplicatePlan{
Plan plan = new Plan(name);


if(!planSet.contains(plan)){
planSet.add(plan);
} else {
throw(new DuplicatePlan("Error, duplicate plan"));
}

return plan;
}

我认为我的 equals()hashCode() 方法导致了这个。目前我正在使用默认覆盖的 Eclipse hashCode()equals(),这就是我得到的:

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj){
return true;
} if (obj == null){
return false;
} if (getClass() != obj.getClass()){
return false;
}
Plan other = (Plan) obj;
if (name == null) {
if (other.name != null){
return false;
}
} else if (!name.equals(other.name)){
return false;
}
return true;
}

这就是 Plan 所做的:

private String name;
private Set<Tables> tablesSet;


public Plan(String name){
this.name = name ;
}

如果用户在 TextField 中设置相同的名称,将会发生以下情况:

newPlan.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent action){
if(!newPlan.getText().isEmpty()){
try {
String name = planName.getText();
plan.createPLan(name);
esquema = esquemas.createPlan(planName.getText());
optionsPlans.getItems().add(plan.getName());
} catch (DuplicatePlan e) {
dialog.errorDialog(planError, duplicate);
}
} else {
dialog.errorDialog(empty, emptySpace);
}
}
});

最佳答案

不得不使用 Answer,因为评论太长了。这在我看来很可疑:

String name = planName.getText();
plan.createPLan(name);
esquema = esquemas.createPlan(planName.getText());

createPlancreatePlan 有什么关系?复制粘贴错误?还是您两次调用相同的方法(这可以解释行为)?

关于java - 添加元素以设置的方法总是抛出自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19552117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com