I have a class of Orders and it has the number of the order, and it has to increase by 1 every time a new order is created.
I tried to use static but it changed the number of all the orders
Any help?
CodePudding user response:
If it is ID generator you need, there is simple solution with combination of static instance variable
public class Order {
private static volatile long nextId = 0L;
private long id;
public Order (){
id = nextId ;
}
}
EDIT
I'll just leave it here for reference Is a volatile int in Java thread-safe?
CodePudding user response:
maybe like that?
public class Order {
private long id;
public Order (long lastId){
id = lastId ;
}
}
so, when you create a new you do Order order = new Order(otherOrder);