添加新对象并生成新的字段ID

时间:2018-02-15 15:34:33

标签: java

我有清单:

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?

4 个答案:

答案 0 :(得分:2)

您可以使用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(); 
  }
}

答案 1 :(得分:1)

使用静态变量说oldId来存储之前的id。将您的Day课程更改为:

public class Day implements Identifiable {
    private static Integer oldId = 0;
    private Integer id;
    private byte isHoliday;

    public Day() {
        this.id = oldId + 1;
        oldId++;
    }
    //getters and setters
}

答案 2 :(得分:1)

您可以使用静态成员和构造函数:

public class Day implements Identifiable {
  static private int maxId = 0;
  final private Integer id;
  private byte isHoliday;

  public Day() {
    this.id = maxId;
    maxId++;
  }
}

每次创建Day的新实例时,其id成员设置为maxId的值,然后maxId递增。

将“id”设为final是一个好主意,因为它用于识别您的对象。

答案 3 :(得分:1)

如果您可以尝试使用简单类型而不是面向对象的类型,即使用Integer而不是int。

public class Day {
    private static int serial = 0; //static means that this is a common field (the same place in memory) for all created objects.
    private final int id; //final means that another value / object can not be assigned to this reference after initializing in the constructor.

    public Day() {
        id = serial++;
    }
    //getters and setters
}