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