简体   繁体   中英

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

eg Reminder-1, Reminder-2 etc....

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

Thank you

As long as there is no concurrency.

private static int reminderID = 1;

public synchronized static String generateUniqueID() {
    String uniqueId = "Reminder-" + reminderID;
    reminderID++;
    return uniqueId;
}
private static final AtomicInteger counter = new AtomicInteger(1);

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

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM