damien535
damien535

Reputation: 637

Integer increment and concat with string

I'm in the process of creating a method to generate a unique id, of type Integer, and was wondering how to do the following.

In my Object I want to call the generateUniqueID method from my setter method. The generateUniqueID will generate an incrementing number and then append it to a string

e.g. Reminder-1, Reminder-2 etc....

I'm not quite sure how to do this though and was wondering if anyone could help?

Thank you

Upvotes: 1

Views: 3363

Answers (4)

jelovirt
jelovirt

Reputation: 5892

private static final AtomicInteger counter = new AtomicInteger(1);

public String generateUniqueID() {
    return "Reminder-" + counter.getAndIncrement();
}

Upvotes: 3

mellamokb
mellamokb

Reputation: 56779

As long as there is no concurrency.

private static int reminderID = 1;

public synchronized static String generateUniqueID() {
    String uniqueId = "Reminder-" + reminderID;
    reminderID++;
    return uniqueId;
}

Upvotes: 5

Ids
Ids

Reputation: 208

Perhaps:

class Classname {
    private static int highestId = 0;
    int object_id;

    public Classname() {
        object_id = highestId++;
    }
}

Would work?

As noted above, this is not threadsafe.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533620

If you have lot of these you can use base 36 encoding.

private final AtomicLong counter = new AtomicLong();

public String generateUniqueID() {
    return "Reminder-" + Long.toString(counter.incrementAndGet(), 36);
}

Upvotes: 1

Related Questions