简体   繁体   English

如何将位组合成一个long以创建唯一ID?

[英]How can I assemble bits into a long to create a unique ID?

I would like to write a utility that will provide me with a relatively unique ID in Java. 我想编写一个实用程序,它将在Java中为我提供一个相对唯一的ID。 Something pretty simple, like x bits from timestamp + y bits from random number. 很简单,例如时间戳记中的x位和随机数中的y位。

So, how would I implement the following method: 因此,我将如何实现以下方法:

long getUniqueID()
{
    long timestamp = System.currentTimeMillis();
    long random = some random long

    ...

    return id;
}

BONUS 奖金

Any suggestions for other easily obtainable information I could use to form my ID? 对我可以用来形成ID的其他易于获得的信息有什么建议吗?

note: I am aware of GUIDs and I know Java has a UUID class, but I don't want something that is 128 bits long. 注意:我知道GUID,并且我知道Java具有UUID类,但是我不想要128位长的东西。

只需剪掉不需要的部分:

return java.util.UUID.randomUUID().getLeastSignificantBits();

What you are trying to do is create a hash function that combines two long values into a single long value. 您试图做的是创建一个将两个长值组合成一个长值的哈希函数 In this case, the uniformity of the hash function will be of utmost importance since collisions in created unique ID values are unacceptable. 在这种情况下,哈希函数的均匀性至关重要,因为创建的唯一ID值中的冲突是不可接受的。 However, if you can compare hash values to previously created identifiers, then collisions can be resolved by modifying the hash until no collision occurs. 但是,如果您可以将哈希值与先前创建的标识符进行比较,则可以通过修改哈希直到没有冲突发生来解决冲突。

For example, you could take the time stamp and perform an exclusive-or (using the caret ^ operator in Java) with the random value. 例如,您可以获取时间戳,并对随机值执行异或 (使用Java中的caret ^运算符)。 If a collision is detected, then add one to the result. 如果检测到冲突,则将结果加一。

If unique in the same JVM is enough then something like this should do the job. 如果在同一个JVM中唯一就足够了,那么应该执行类似的操作。

public class UniqueID {
  static long current= System.currentTimeMillis();
  static public synchronized long get(){
    return current++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM