Reputation: 2795
I have to make a class that has int member which is unique for every object of that class. So:
public class Cls {
private int id;
public Cls(){id = unique number;}
}
So when I make x number of Cls
objects, I must be sure that no classes have the same id. But I want to avoid making global variable in main, and setting id one by one. If it is possible it would be great if id can be set in the constructor.
Upvotes: 2
Views: 737
Reputation: 3919
Does it have to be a numeric uid? Also, are you looking for unique across a jvm or unique across all runs of the app? Are you looking for unique only for live objects or across the entire run of the app?
For a limited set of answers (no, across jvm only, only for live objects), simplest would be to use the Object id of the object. But this is not numeric, and can be reused after an object dies. However you get gaurenteed uniqueness for free.
Upvotes: 0
Reputation: 56724
Use a static variable and increment it:
public class Cls {
private static int count = 0;
private int id;
public Cls() {
id = count;
count++;
}
}
The first object will have id = 0
, the second one will have id = 1
, etc.
Limitation: This method is the simplest one, but it won't work if you want to have an application that uses many threads.
If you are in a multithreading context, you'll need to be sure that you have some expected results. Some possible methods:
1) Use a class from java.util.concurrent.atomic
( E.g. AtomicInteger
) (according to OldCurmudgeon)
2) Instead of count++
, call a synchronized method that has the following structure:
public static synchronized void incrementCount() {
count++;
}
3) Use an additional object for synchronization:
private static final Object lock = new Object();
and then use it to synchronize the increment operation:
public void increment() {
synchronized(lock) {
count++;
}
}
Upvotes: 2
Reputation: 65889
You can hold a static
value containing the last value you used and always increment it every time you use it. An AtomicInteger
is excellent for this because it is thread safe and does not require locks if used in a multi-thread environment.
public class Cls {
// The last id I used.
private static final AtomicInteger nextId = new AtomicInteger();
// My id
private final int id = nextId.getAndIncrement();
public Cls() {
}
}
Upvotes: 5
Reputation: 22663
The UUID class provides a simple means for generating unique ids.
import java.util.UUID;
public class GenerateUUID {
public static final void main(String... aArgs){
UUID uniqueID = UUID.randomUUID();
log("unique ID: " + uniqueID);
}
private static void log(Object aObject){
System.out.println( String.valueOf(aObject) );
}
}
Upvotes: 4
Reputation: 1
You can either create a surrounding structure which manages the uniqueness of that index or use a UUID. A UUID still has a very slight chance of collision, but this shouldn't be a problem with small amountd of data.
Upvotes: 0