How to prevent multiple instances of an object from having the same property in Java


Nicole Foster:

Below is my code snippet

Account acc1 = new Account ("123", "James", "Savings");
Account acc2 = new Account ("234", "James", "Checking");
acc1.setNickName("James Account");
acc2.setNickName("James Account");


//Nick Name Method
private String nickName;

public void setNickName (String name)
{
    nickname = name;

}

My question is how can I prevent acc2the NickName value of the object from being the same acc1?

I want to make sure setNickNamethere is a mechanism in that method to prevent two object instances from being the same.

Ashishkumar Singh

You can create a static object Setin your Accountclass , and every time you nicknameadd a static object , check if a static object already exists . If not, set the value. If it doesn't exist then you can have your own logic (which I throw out 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 @Makoto pointed out, defining the object Setin the Accountclass will cause all account objects to have access to other account's nicknames. If you are concerned about data hiding, we should create a new class statement AccountManagerwith logic to identify duplicates nickNamedelegated to it .

Related


How to prevent multiple instances of Java annotations in a class

D. Bertini: I have Java annotation type like this: import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(RUNTIM

How to prevent multiple instances of Java annotations in a class

D. Bertini: I have Java annotation type like this: import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(RUNTIM

How to prevent multiple instances of Java annotations in a class

D. Bertini: I have Java annotation type like this: import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(RUNTIM

Prevent multiple script instances from appearing at the same time

Marcus PHP does not provide multithreading by default for our application, but it is possible that 2 or more users click the same link at the same time, or in my case, send multiple API requests at the same time. I have scripts that create fairly large files w