標籤:res bsp random sim long 返回 str new lan
在開發時要給某些表加上編號,而且編號是唯一的,自己用時間產生了下,覺得可能存在並發情況。所以在網上查了一下,就是隨機產生。方法如下:
//方法一(用目前時間精確到毫秒,截取任意幾位)
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSS");
String formDate =sdf.format(date);
System.out.println(formDate);
String no = formDate.substring(10);
System.out.println(no);
//方法二(隨機產生)
int[] array ={0,1,2,3,4,5,6,7,8,9};
Random rand = new Random();
for (int i = 10; i > 1; i--) {
int index =rand.nextInt(i);
int tmp =array[index];
array[index] = array[i - 1];
array[i - 1] = tmp;
}
int result = 0;
for(int i = 0; i < 6; i++)
result = result * 10 + array[i];
System.out.println(result);
//方法三:利用時間戳記得到8位不重複的隨機數
long nowDate = new Date().getTime();
String sid = Integer.toHexString((int)nowDate);
System.out.println(sid);
/*其中:java.lang.Integer.toHexString() 方法返回為不帶正負號的整數基數為16的整
*/參數的字串表示形式。以下字元作為十六進位數字:0123456789ABCDEF。 }
Java產生不重複的數的方法