Each enum
value (you have got three) exists only once and each time you are using one of them you are just reusing one of those three values by creating a reference, there are no copies.
This means if you change the ticketId
on the FirstClass
value, it is changed wherever that value is referenced.
It seems you want to model a little ticket system. Each object having an own identity should be modeled as a class
which has a property for the type and the id:
public class Ticket {
private Long ticketId;
private TicketType type;
public Long getTicketId() {
return ticketId;
}
public void setTicketId(Long ticketId) {
this.ticketId = ticketId;
}
public TicketType getType() {
return type;
}
public void setType(TicketType type) {
this.type = type;
}
}
public enum TicketType {
FirstClass(0),
PremiumClass(1),
EconomyClass(2);
private final int elementId;
Ticket(int elementId) {
this.elementId = elementId;
}
public int getElementId() {
return elementId;
}
}
Then you can use it this way:
public void myMethod() {
ArrayList<Ticket> tickets = new ArrayList<>();
Ticket ticket = new Ticket();
ticket.setType(TicketType.FirstClass);
ticket.setTicketId(1L);
tickets.add(ticket);
ticket = new Ticket();
ticket.setType(TicketType.FirstClass);
ticket.setTicketId(2L);
tickets.add(ticket);
}
I don't know why you need an elementId
on the ticket type, that's why I just left it there (without using it). Probably you should rename ticketId
to just id
to keep it simple.
If the ticket's type
or ticketId
are never changed after assigning them you may want to remove the setters and assign the values in the constructor of Ticket
(and make the attributes final
).
Even if it's ok that they are changeable, you may introduce such a constructor to have code which is better readable:
In Ticket.java:
public Ticket(Long ticketId, TicketType type) {
this.ticketId = ticketId;
this.type = type;
}
Then you can write:
tickets.add(new Ticket(1L, TicketType.FirstClass));
If ticket is a persisted entity (which gets inspected by a framework like Hibernate) you might have to keep a no-args constructor to make it instantiable when loading it from a database.