【问题标题】:I want to create unique user id我想创建唯一的用户 ID
【发布时间】:2020-01-16 15:09:46
【问题描述】:

我只是创建唯一的 ID,但使用随机数。但我想创建像 jason-001、smith-002 等这样的 id。

Integer user_id= new Random().nextInt();

//implementation
reference_uploaded_by.getRef().setValue(name.getText().toString() + "-" + user_id);

【问题讨论】:

  • 独特随机。你确定吗?
  • 如果此 ID 用于标识,为什么不使用 UUID?喜欢id = UUID.randomUUID().toString();
  • 糟糕的标题。重写以针对您的技术问题。
  • 您是否在问如何最好地创建一个唯一的用户 ID?或者您是在问具体如何创建一个由名称和序列号组成的字符串?努力使您的问题集中且非常具体。

标签: java android-studio


【解决方案1】:

您可以使用AtomicLong#incrementAndGet 作为计数器。 “Atomic”表示类是thread-safe

AtomicLong userIdIncrementor = new AtomicLong(previouslyUsedNumber);

使用该对象为每个新用户获取递增的数字。

long number = userIdIncrementor.incrementAndGet();
String userId = userName + String.format("%03d", number);

此代码假定您的用户永远不会超过一千,您在问题中指定的数字只有三位数。

有关格式化整数的详细信息,请参阅this Answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2012-04-26
    相关资源
    最近更新 更多