Elegant way to assign object id in Java

后端 未结 4 1616
感情败类
感情败类 2020-12-09 03:52

I have a class for objects ... lat\'s say apples.

Each apple object mush have a unique identifier (id)... how do I ensure (elegantly and efficiently) that newly crea

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 04:43

    Use java.util.UUID.randomUUID()

    It is not int, but it is guaranteed to be unique:

    A class that represents an immutable universally unique identifier (UUID).


    If your objects are somehow managed (for example by some persistence mechanism), it is often the case that the manager generates the IDs - taking the next id from the database, for example.

    Related: Jeff Atwood's article on GUIDs (UUIDs). It is database-related, though, but it's not clear from your question whether you want your objects to be persisted or not.

提交回复
热议问题