我正在寻找在Java中创建唯一ID作为字符串的最佳方法。
任何指导都很感激,谢谢。
我应该提到我使用的是Java 5。
我正在寻找在Java中创建唯一ID作为字符串的最佳方法。
任何指导都很感激,谢谢。
我应该提到我使用的是Java 5。
当前回答
具有计数信息的唯一ID
import java.util.concurrent.atomic.AtomicLong;
public class RandomIdUtils {
private static AtomicLong atomicCounter = new AtomicLong();
public static String createId() {
String currentCounter = String.valueOf(atomicCounter.getAndIncrement());
String uniqueId = UUID.randomUUID().toString();
return uniqueId + "-" + currentCounter;
}
}
其他回答
java.util.UUID: toString()
创建UUID。
String uniqueID = UUID.randomUUID().toString();
如果你想要简短的、人类可读的id,并且只需要它们在每次JVM运行时是唯一的:
private static long idCounter = 0;
public static synchronized String createID()
{
return String.valueOf(idCounter++);
}
编辑:评论中建议的替代方案-这依赖于底层的线程安全“魔法”,但更可扩展,同样安全:
private static AtomicLong idCounter = new AtomicLong();
public static String createID()
{
return String.valueOf(idCounter.getAndIncrement());
}
String name,password;
public int idGen() {
int id = this.name.hashCode() + this.password.hashCode();
int length = String.valueOf(id).length();
int Max_Length = 5;
if(String.valueOf(id).length()>Max_Length)
{
id = (int) (id /Math.pow(10.0,length - Max_Length ));
}
return id;
}
以下是我的两美分价值:我之前实现了一个IdFactory类,它创建的id格式为[主机名]-[应用程序启动时间]-[当前时间]-[鉴别器]。这在很大程度上保证了id在JVM实例中是唯一的,同时保持id可读(尽管相当长)。以下是代码,以防它有任何用处:
public class IdFactoryImpl implements IdFactory {
private final String hostName;
private final long creationTimeMillis;
private long lastTimeMillis;
private long discriminator;
public IdFactoryImpl() throws UnknownHostException {
this.hostName = InetAddress.getLocalHost().getHostAddress();
this.creationTimeMillis = System.currentTimeMillis();
this.lastTimeMillis = creationTimeMillis;
}
public synchronized Serializable createId() {
String id;
long now = System.currentTimeMillis();
if (now == lastTimeMillis) {
++discriminator;
} else {
discriminator = 0;
}
// creationTimeMillis used to prevent multiple instances of the JVM
// running on the same host returning clashing IDs.
// The only way a clash could occur is if the applications started at
// exactly the same time.
id = String.format("%s-%d-%d-%d", hostName, creationTimeMillis, now, discriminator);
lastTimeMillis = now;
return id;
}
public static void main(String[] args) throws UnknownHostException {
IdFactory fact = new IdFactoryImpl();
for (int i=0; i<1000; ++i) {
System.err.println(fact.createId());
}
}
}