java - 添加新对象并生成新字段 ID

标签 java

我有 list :

private List<Day> days = new ArrayList<>();

我的Day对象:

public class Day implements Identifiable {
    private Integer id;
    private byte isHoliday;
    //getters and setters
}

我添加了一个新的 Day 对象,例如:

Day day = new Day();
day.setHoliday(1);
days.add(day);

如何在添加新元素时自动设置字段id,该字段等于前一个元素+ 1? 也许我可以使用 Java 8 Streams?

最佳答案

您可以使用 AtomicInteger() - 它是线程安全的。

 public class Day implements Identifiable {
  private static AtomicInteger count = new AtomicInteger(0);
  private int id;
  private byte isHoliday;

  public Day() {
    this.id = count.incrementAndGet(); 
  }
}

关于java - 添加新对象并生成新字段 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48810856/

相关文章:

java - 维基数据 API 总是返回空指针异常

java - 如何让 java 程序的命令提示符中显示英镑符号 (£)?

java - 一个简单的 string.split() 出了可怕的错误

java - 传递在 Activity 之间单击的 ListView 项目

java - JAX-WS 使用@SchemaValidation 在 WebLogic 中验证模式

java - 使图像适合 ImageButton

java - Jackson 同一类的不同 mixin

Java : replacing all URLs with anchor tags that aren't already in anchor tags

java - Struts 1到 Spring 迁移-策略

java - 你如何在用 java 编写的 selenium webdriver 程序中使用 firefox 插件?