Java-为对象的每个实例赋予唯一编号 [英] Java- give every instance of object an unique number
问题描述
我在用Java编写一个简单的程序时遇到麻烦.
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;
public static Integer movieNumber = 0;
public final Integer currentMovieNumber;
public Ticket(String movieTitle) {
currentMovieNumber = movieNumber++;
this.movieTitle = movieTitle;
}
}
现在,当我在另一个类中调用票证并运行程序以获取ID的编号时,它们都是一样的. 如果我叫出3张票,则每个id/movieNumber为3,当我叫出2张票时,id为2. 有人可以帮我吗?我以为使用static和final会有所帮助,但我想我缺少了一些东西.
Now when I call the ticket out in another class and run the program to get the numbers of the id's, they're all the same. If I call out 3 tickets, every id/movieNumber is 3, when I call out 2 tickets, the id will be 2. Can someone please help me with this ? I thought using static and final would help me but I guess there's is something I am missing.
推荐答案
听起来好像您正在从另一个类中查看movieNumber
,这是不合适的.我会这样写:
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;
}
}
现在这些字段是私有的,其他类不能看到错误的值-相反,它们只能获取特定票证的ID和标题.他们没事看着柜台.
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.
其缺点是您不能轻易重置计数器或在下次运行程序时恢复计数器等.为此,您可能需要具有实例的TicketFactory
计数器的em>字段和createTicket
的实例方法,该方法通过为其分配下一个ID等来创建票证.Ticket
本身不知道计数器.
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.
这篇关于Java-为对象的每个实例赋予唯一编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!