1.17. Generating Unique Numeric Identifiers
Problem
You need to generate numeric and alphanumeric identifiers.
Solution
Use IdentifierUtils to create an
IdentifierFactory with both numeric and
alphanumeric identifiers. Example 1-15 demonstrates
the use of a LongIdentifierFactory to create
unique numeric identifiers.
Example 1-15. Using a LongIdentifierFactory to create unique numeric identifiers
import org.apache.commons.lang.util.IdentifierUtils;
import org.apache.commons.lang.util.LongIdentifierFactory;
LongIdentifierFactory idFactory = factory.longGenerator(false, 0);
System.out.print( "Identifiers: " );
for( int i = 0; i < 10; i++ ) {
System.out.println( idFactory.nextLongIdentifier( ) + " " );
}This code will create 10 unique numeric identifiers and print them out on one line, producing the following output:
Identifiers: 0 1 2 3 4 5 6 7 8 9
Discussion
If you need a unique alphanumeric identifier,
create a StringIdentifierFactory. This factory is
created by calling the stringAlphanumericIdentifierFactory( )
method, passing true if you want the
factory to wrap when it reaches a maximum value. The second parameter
to this method specifies the length of the alphanumeric identifier;
in this case, a length of four is specified. (See Example 1-16.)
Example 1-16. Using an IdentifierGenerator to create unique alphanumeric identifiers
import org.apache.commons.lang.util.IdentifierUtils; import org.apache.commons.lang.util.StringIdentifierFactory; StringIdentifierFactory idFactory = IdentifierUtils. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access