简体   繁体   English

当我声明和初始化类的对象时,如何自动增加类中的字段?

[英]How to auto-increment a field in my class when I declare and initialize an object of the class?

I have 3 classes in my Java application, One representing a Medical Policy:我的 Java 应用程序中有 3 个类,一个代表医疗政策:

public class MedicalPolicy implements PolicyType {
    private int id;
    // and some other fields

    public MedicalPolicy(final LocalDate effective,final LocalDate expiry,final ArrayList<Beneficiary> beneficiaries){
          //Constructor that does NOT set/initialize the id field
    }
}

Another class which represents the Motor Policy:另一个代表 Motor Policy 的类:

public class MotorPolicy implements  PolicyType{

    private int id;
    // and some other fields

    public MotorPolicy(final LocalDate effective,final LocalDate expiry,final double vehiclePrice){
        //Constructor that does NOT set/initialize the id field
    }
}

And the 3rd class contains the main() method.第三个类包含main()方法。

Every time I declare and initialize a Medical Policy object in my main() I want the id of the Medical Policy to increment by 1, the same for the Motor Policy, ie if I declare 2 Medical Policy objects in my main() I want the value of 1st Medical Policy to have the id equal to 1 and the 2nd Medical Policy to have the id 's value set to 2, and if I declare 3 Motor Policy, I want the 1st to have it's id equal to 1, the 2nd's id equal to 2 and the 3rd's id equal to 3.每次我在main()声明和初始化 Medical Policy 对象时,我都希望 Medical Policy 的id增加 1,Motor Policy 也是如此,即如果我在main()声明了 2 个 Medical Policy 对象,我想要第一个医疗政策的值使id等于 1,第二个医疗政策的值将id的值设置为 2,如果我声明 3 Motor Policy,我希望第一个医疗政策的id等于 1,第 2 个的id等于 2,第 3 个的id等于 3。

How can I accomplish that?我怎样才能做到这一点?

PS: There is no prob if I have to set/initialize it from the constructor, what's important is that I shouldn't pass it's value as a constructor parameter. PS:如果我必须从构造函数设置/初始化它,则没有问题,重要的是我不应该将它的值作为构造函数参数传递。

As I have suggested in my comment, I would add an AtomicInteger to count the number of constructor calls:正如我在评论中所建议的,我会添加一个AtomicInteger来计算构造函数调用的数量:

public class MedicalPolicy implements PolicyType {
    private static final AtomicInteger counter = new AtomicInteger();

    private final int id;

    public MedicalPolicy(
            final LocalDate effective,
            final LocalDate expiry,
            final ArrayList<Beneficiary> beneficiaries){
        id = counter.incrementAndGet();
    }
}

The reason for using an AtomicInteger is thread-safety.使用AtomicInteger的原因是线程安全。

Notice, however, that this implementation does only count how often the constructor was called.但是请注意,此实现仅计算调用构造函数的频率。 To get a count of reachable instances of a given class there are two solutions coming to my mind.为了计算给定类的可达实例的数量,我想到了两种解决方案。 One involves overriding finalize() (which is deprecated in Java 13).一种涉及覆盖finalize() (在 Java 13 中已弃用)。 The other uses a List of PhantomReference s to track reachable instances.另一个使用PhantomReference List来跟踪可达实例。

You can use AtomicInteger , which is used in applications such as atomically incremented counters.您可以使用AtomicInteger ,它用于诸如原子递增计数器之类的应用程序。

public class MedicalPolicy implements PolicyType {
  private static final AtomicInteger count = new AtomicInteger(); 
    // and some other fields

    public MedicalPolicy(final LocalDate effective,final LocalDate expiry,final ArrayList<Beneficiary> beneficiaries){
          //Constructor that does NOT set/initialize the id field
         count.incrementAndGet(); 
    }
}

Use a private static int as an instance variable使用private static int作为实例变量

Inside the constructor you set the id to the serial and add one to the serial.在构造函数中,您将 id 设置为序列号并将其添加到序列号。

public class MedicalPolicy implements PolicyType {
    private static int serial = 1;
    private int id;
    // and some other fields

    public MedicalPolicy(final LocalDate effective,
                         final LocalDate expiry,
                         final ArrayList<Beneficiary> beneficiaries){
      this.id = serial++;
      // Other constructor stuff
    }
}

If your class needs to be thread safe, use an AtomicInteger as Turing85 mentioned.如果您的类需要线程安全,请使用 Turing85 提到的AtomicInteger

Could you not create a List, then each object of that class would be associated to its incrementing location in the index.你能不能不创建一个列表,那么该类的每个对象都将与其在索引中的递增位置相关联。 eg.例如。 listName.get(obj num-1) since the first object will be stored at index of 0. Also listName.size() would return a value so you could track how many you had. listName.get(obj num-1) 因为第一个对象将存储在索引 0 处。此外 listName.size() 将返回一个值,以便您可以跟踪您拥有的数量。

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

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