首页 > 编程知识 正文

java自动生成数字编号,什么时候用自增id做主键

时间:2023-05-06 10:28:57 阅读:29035 作者:4147

根据长类型的用户ID生成6位随机邀请代码,可以根据邀请代码计算用户ID。 代码如下。

//

//不重复随机字符串类

//

公共类串行编号helper

{

/*自定义进制数(选择所需的进制数,不能重复。 另外,最好避开0、1等容易混淆的文字(*/

privatestaticreadonlychar [ ] r=new char [ ] { ' q '、' w '、' e '、'8'、' s '、'2'、' d '、' z ',

x、9、c、7、p、5、k、3、m、u、f、r、4、v、y。

/**定义用于补充邀请长度的字符()该字符前面有计算的邀请,后面有补充) /

私密静态只读通道b=' a ';

/**进制长度*/

privatestaticreadonlyintbinlen=r.length;

/**邀请函长度*

私有静态只读int s=6;

//

根据//id生成随机代码

//

///ID

///

publicstaticstringtoserialcode (长码) )。

{

char[] buf=new char[32];

int charPos=32;

wile((id/Binlen )0) ) ) )。

{

intind=(int ) ) id % binLen );

buf[--charPos]=r[ind];

id /=binLen;

}

BUF[--Charpos]=r[(int ) (id % binLen ) ];

stringstr=newstring(buf,charPos,) (32 - charPos );

//长度不够的自动随机补充

if(str.Lengths ) )。

{

stringbuilder sb=new stringbuilder (;

sb.append(b );

Random rnd=new Random (;

for(intI=1; i s - str.Length; I )

{

sb.append(r[rnd.next ) Binlen ) ];

}

str =sb.ToString (;

}

返回str;

}

//

//从随机代码生成ID

//

//

//

publicstaticlongcodetoid (字符串代码)。

{

char[] chs=code.ToCharArray (;

long res=0L;

for(intI=0; i chs.Length; I )

{

int ind=0;

for(intj=0; j binLen; j )

{

if(CHS[I]==r[j] )

{

ind=j;

布雷克;

}

}

if(CHS[I]==b ) ) ) )

{

布雷克;

}

if(I0 ) )。

{

res=res * binLen ind;

}

else

{

res=ind;

}

}

返回RES;

}

}

上面6位邀请代码可以显示的最大ID为728999999(「hhhhhh”)、729000000 (“w qqqq”)。

使用与上述方法相同的id生成的邀请函不唯一。 想要唯一的话,定义补码字符串就可以了。

//补码字符串

privatestaticfinalstringe=' atgsghj ';

/*

*根据id生成6位随机代码

* @param id ID

* @return随机码

*/

publicstaticstringtoserialcode {

char[] buf=new char[32];

int charPos=32;

while((id/Binlen )0) {

intind=(int ) ) id % binLen );

buf[--charPos]=r[ind];

id /=binLen;

}

BUF[--Charpos]=r[(int ) (id % binLen ) ];

stringstr=newstring(buf,charPos,) (32 - charPos );

//长度不够自动完成

if(str.length ) ) s ) {

stringbuilder sb=new stringbuilder (;

sb.append(e.subsequence(0,s-str.length ) );

str=sb.toString (;

}

返回str;

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。