Java- give every instance of object an unique number

后端 未结 2 923
一生所求
一生所求 2021-01-25 23:14

I\'m having trobule writing a simple program in java.

I have a class called ticket, where I have:

public class Ticket {
public String movieTitle = null;
         


        
相关标签:
2条回答
  • 2021-01-25 23:58

    I think it is because you are using wrapper classes, i.e. Integer instead of int, which means that inside the class field you are only storing the reference. That means that in your constructor you are actually linking each class' currentMovieNumber to the static movieNumber so that when you increment the movieNumber, since all the instances' numbers point to it, every Ticket will have the same incremented number.

    Using int instead of Integer should solve this.

    0 讨论(0)
  • 2021-01-26 00:02

    It sounds like you're looking at movieNumber from your other class, which isn't appropriate. I would write it like this:

    import java.util.concurrent.atomic.AtomicInteger;
    
    public class Ticket {
        private static final AtomicInteger ticketCounter = new AtomicInteger();
        private final int ticketId;
        private final String movieTitle; // Or a reference to a Movie...
    
        public Ticket(String movieTitle) {
            this.movieTitle = movieTitle;
            this.ticketId = ticketCounter.incrementAndGet();
        }
    
        public int getTicketId() {
            return ticketId;
        }
    
        public String getMovieTitle() {
            return movieTitle;
        }
    }
    

    Now that the fields are private, other classes can't look at the wrong value - instead, they can only get at the ID for a particular ticket, and the title. They have no business looking at the counter.

    The downside of this is that you can't easily reset the counter, or resume it when you next run the program, etc. To achieve that, you might want a TicketFactory which has an instance field for the counter, and an instance method of createTicket which creates a ticket by assigning it the next ID etc. Ticket itself then wouldn't know about the counter.

    0 讨论(0)
提交回复
热议问题