在Java中分配对象ID的优雅方式 [英] Elegant way to assign object id in Java

查看:251
本文介绍了在Java中分配对象ID的优雅方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象类... lat说苹果。

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

每个苹果对象都有一个唯一的标识符(id)...我该如何确保(优雅高效)新创建的具有唯一ID。

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

谢谢

推荐答案

在你的Apple类中有一个 static int nextId 并在你的构造函数中增加它。

have a static int nextId in your Apple class and increment it in your constructor.

它可能是谨慎确保您的递增代码是原子的,因此您可以执行类似的操作(使用AtomicInteger)。这将保证如果两个对象完全同时创建,它们不会共享相同的Id。

It would probably be prudent to ensure that your incrementing code is atomic, so you can do something like this (using AtomicInteger). This will guarantee that if two objects are created at exactly the same time, they do not share the same Id.

public class Apple {
    static AtomicInteger nextId = new AtomicInteger();
    private int id;

    public Apple() {
        id = nextId.incrementAndGet();
   }
}

这篇关于在Java中分配对象ID的优雅方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆