user1825608
user1825608

Reputation:

Can I mark object field as unique in Java

As in the subject Can I mark object field as unique in Java? I want to have unique id in the class.

Upvotes: 1

Views: 3730

Answers (4)

Philipp
Philipp

Reputation: 69663

When you don't care about the content of your unique field except for the fact that they have to be unique, you can use the solution by nukebauer.

But when you want to set the value manually and throw an exception when the value is already used by another instance of the class, you can keep track of the assigned values in a static set:

class MyObject {
    private Integer id;
    private static Set<Integer> assignedIds = new HashSet<Integer>();

    public void setId(int id) throws NotUniqueException {
         if (!this.id.equals(id) {
             if (assignedIds.contains(id) {
                 throw new NotUniqueException();
             }
             assignedIds.add(id);
             this.id = id;
         }
    }
}

By the way: Note that both options are not thread-safe! That means that when two threads create an instance / set an ID at exactly the same time, they might still get the same ID. When you want to use this in a multi-threading environment, you should wrap the code in a synchronized block which synchronizes on the static variable.

Upvotes: 0

Philip Tenn
Philip Tenn

Reputation: 6073

Your question was a bit vague, but I am going to attempt to answer it based on the limited information.

I want to have unique id in the class.

If you are looking to specify a Unique ID for the class for persistence through a well-known framework such as Hibernate, you can do so through the HBM mapping or @Id annotation.

If you are looking to ensure that an instance of a particular Class is unique (from a runtime perspective), then you should override the .equals method and do the comparison in .equals based on the field that you are using as the "unique id of the class". If you wanted some sort of development-time indicator that particular field is your "unique ID", you could always create a custom annotation.

Here is an excellet answer from a different StackOverflow post regarding how to override .equals and .hashCode using the Apache Commons Lang library. You can use this and just modify the .equals override to compare on whatever field you are using as your "Unique ID".

Upvotes: 0

nukebauer
nukebauer

Reputation: 331

You can create unique IDs with a static variable which you increment on each object creation and assign to your ID variable:

private static int globalID = 0;
private int ID;
public obj()
{
   globalID++;
   this.ID = globalID;
}

Upvotes: 4

Kai
Kai

Reputation: 39641

No, that is not possible. You have to manage that in a Controller class.

Upvotes: 1

Related Questions