You can create a static Set object in your Account class and every time a nickname is added, you check if already one exists. If it doesn't, then set the value. If it doesn't exists, then you can have your own logic(I have thrown a IllegalArgumentException)
class Account {
private static Set<String> nickNameSet = new HashSet<>();
public void setNickName(String nickName) {
if(nickNameSet.add(nickName))
{
this.nickName = nickName;
}
else {
throw new IllegalArgumentException("Nick Name already exists");
}
}
}
As pointed out by @Makoto, defining the Set object in the Account class will lead to all account object having access to nickname of other accounts. If data hiding is your concern, we should create a new class say AccountManager and have the logic of identifying duplicate nickName delegated to it.
manpreet
Best Answer
3 years ago
Below is my code snippet
My question is how can I prevent
acc2object from having the value of NickName same as that ofacc1?I want to ensure that in the
setNickNamemethod there is a mechanism to prevent two object instances from being the same.