java 唯一实例,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;

}

}

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.

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值