朋友和同事。我有以下類:如何禁止使用相同參數創建兩個類對象?
public class Department {
private String departmentName;
private int moneyForDepartment;
public Department(String departmentName, int moneyForDepartment){
if (moneyForDepartment < 0){
throw new IllegalArgumentException("invalid value");
}
this.departmentName = departmentName;
this.moneyForDepartment = moneyForDepartment;
}
public Department(){
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public int getMoneyForDepartment() {
return moneyForDepartment;
}
public void setMoneyForDepartment(int moneyForDepartment) {
this.moneyForDepartment = moneyForDepartment;
}
}
和例如我將創建該類的兩個對象:
Department dep1 = new Department("Storage", 100000);
Department dep2 = new Department("Storage", 200000);
請告訴我,我怎麼能禁止的情況下,當創建類對象具有相同第一個參數的這個類的對象是否已經存在?
感謝路易斯,這就是非常好的解決方案!) –