0

I want to implement a functionality that auto increment an alpha numeric id in a Java program.

The ids types are Strings, have only digits and lower case latin letters, and is case insensitive.

Basically, I want a function called static String next(String id) that gives what should be the next id.

The id should increase from right to left, and new characters should be added on the left.

For example

assertEquals("1", IdUtils.next("0"));
assertEquals("a", IdUtils.next("9"));
assertEquals("10", IdUtils.next("z"));
assertEquals("10", IdUtils.next("0z"));
assertEquals("100", IdUtils.next("zz"));
assertEquals("zz1", IdUtils.next("zz0"));
assertEquals("zza", IdUtils.next("zz9"));

Thanks in advance.

2 Answers2

2

A number with digits and lower case latin letters is a base-36 number, which is an extension of base-16, also known as hex.

So to increment the base-36 number, parse it, increment it, and convert back to text.

static String next(String id) {
    return Long.toString(Math.incrementExact(Long.parseLong(id, 36)), 36);
}

Test

System.out.println(next("0"));
System.out.println(next("9"));
System.out.println(next("z"));
System.out.println(next("zzzzzz"));
System.out.println(next("dif5613ug"));
System.out.println(next("1y2p0ij32e8e6"));
System.out.println(next("1y2p0ij32e8e7")); // Long.MAX_VALUE, so will overflow

Output

1
a
10
1000000
dif5613uh
1y2p0ij32e8e7
Exception in thread "main" java.lang.ArithmeticException: long overflow
Andreas
  • 154,647
  • 11
  • 152
  • 247
1

If you're going to have an "current ID" variable that you increment, then it's better to keep that state in an AtomicLong instead of a String. It's faster, and much easier to make thread-safe:

... 
AtomicLong m_nextId = new AtomicLong();

static String next() {
    long idnum = m_nextId.getAndIncrement();
    return Long.toString(idnum,36);
}
Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87