Jan
Jan

Reputation: 33

UUID every run is changing

I have an issue. I created the class "User" and in the constructor, I put the name which I have to write and the id which should be generated when I create an object. Unfortunately, I have created one object and every time when I run the code the UUID is changing the id. How can I write the code in the constructor to create one object ID which will not be changing every run?

public class User {
    private String name;
    private UUID id;

    public User(String name) {
        this.name = name;

        this.id = UUID.randomUUID();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return String.valueOf(id);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equals(name, user.name) && Objects.equals(id, user.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, id);
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                '}';
    }
};








public class App {
    public static void main(String[] args) {
        User jan = new User("Jan");
        System.out.println(jan);
}

The output:

User{name='Jan', id='089fb1bf-fc15-4af6-b8e9-0d9e88aaa392'}

User{name='Jan', id='24a4214c-f9b2-49b5-ae27-0c41edcaf5b1'}

Upvotes: 0

Views: 541

Answers (1)

hooknc
hooknc

Reputation: 5001

From the comments, the problem is due to the fact that you're creating a new random UUID in your constructor:

public User(String name) {

    this.name = name;
    this.id = UUID.randomUUID();
}

To fix the randomness of the identifier, I would suggest adding the UUID as part of the constructor:

public User(UUID id, String name) {

    this.id = id;
    this.name = name;
}

This way, you can always control the value of the identifier used.

In the long run, depending on how you architect your application, that identifier could come from a Factory object or a database.

Upvotes: 1

Related Questions