我有 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/