public static long generateLong ( int length ) { if ( length <= 0 || length > 19 ) { throw new IllegalArgumentException ( "Can't generate random id with length: " + length ) ; } SecureRandom random = new SecureRandom ( ) ; StringBuilder sb = new StringBuilder ( length ) ; // 1st digit should not be a 0 or 9 if desired length is 19 (as max long is: 9223372036854775807) if ( length == 19 ) { sb . append ( NUMBERS_NO_NINE_AND_ZERO . charAt ( random . nextInt ( NUMBERS_NO_NINE_AND_ZERO . length ( ) ) ) ) ; } else { sb . append ( NUMBERS_NO_ZERO . charAt ( random . nextInt ( NUMBERS_NO_ZERO . length ( ) ) ) ) ; } // all other digits can contain a 0 for ( int i = 1 ; i < length ; i ++ ) { sb . append ( NUMBERS . charAt ( random . nextInt ( NUMBERS . length ( ) ) ) ) ; } return Long . parseLong ( sb . toString ( ) ) ; }
Generates non negative long key of maximum length 18