如何在java中生成有序的序列号

时间:2016-07-12 08:46:59

标签: java

如何在java程序中生成有序的顺序唯一ID。 输出应该是:  这里是输出中的示例输出 Mys2016vj01 ,01应该增加到年份。 2016年之后应该增加到2017年等等 那么当常数vj号后的年份变化应该重置为01

1 个答案:

答案 0 :(得分:0)

//Initialize it as a static field in the class where you want to generate random number.
private static final UniqueParamBuilder UNIQUE_PARAM_BUILDER = new UniqueParamBuilder();

public String buildNextUniqueNumber() {
     //Params can be final depending on your context.
     String param1 = "Mys";
     String param2 = "vj";

     int year = LocalDateTime.now().getYear();//Java 8. If Java 7, check this

I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible?

     String yearParam = year + "";
     int uniqueNumber = UNIQUE_PARAM_BUILDER.getNext(year);
     String uniqueParam = String.format("%01d", uniqueNumber); //Check this to see how start string with leading zeros.

How can I pad an integers with zeros on the left?

     String result = param1 + yearParam + param2 + uniqueParam;
     return result;
}

public class UniqueParamBuilder {

    private static final YEAR_TO_START = 2015;
    private static final int START_CONTER = 0;

    private int previousYear = YEAR_TO_START;
    private int counter = START_CONTER ;

    public int getNext(int year) {
        if (year > previousYear) {
             previousYear = year;
             resetCounter();
        }
        counter++;//Start counter with 1.
        return counter;
    }

    private void resetCounter() {
         counter = START_CONTER ;
    }
}