I have written the following class for my program:
public class RefGen {
private static String refNo;
protected static void generate(){
//Create array to store reference
ArrayList<String> refList = new ArrayList<>();
//Get date and set output format
DateFormat dateFormat = new SimpleDateFormat("yyMMdd");
Date curDate = new Date();
//Variables
String clientKey = InGenUI.clientText.getText();
String refDate = dateFormat.format(curDate);
String refType = InGenUI.typeCombo.getSelectedItem().toString();
String userName = InGenUI.userCombo.getSelectedItem().toString();
String ref;
int n = 1;
//Create Reference
refNo = clientKey.toUpperCase() + "/" + refDate + "/" + refType + "/" + userName + "/" + Integer.toString(n);
//Check to see if refNo already exists in array
while (refList.contains(refNo)) {
n = n + 1;
refNo = clientKey.toUpperCase() + "/" + refDate + "/" + refType + "/" + userName + "/" + Integer.toString(n);
refList.add(refNo);
}
refList.add(refNo);
System.out.println(refList);
}
public static String reference(){
return refNo;
}
}
The purpose of this class is to generate a unique reference number and store it in an array. Before doing so, it needs to check to see if the array already contains the value. If not, n is incremented by 1 until refNo becomes a unique value that does not exist in the array.
RefGen.reference() is called by genButton in InGenUI.java which output's refNo's value to clientLabel also in InGenUI.java:
private void genButtonActionPerformed(java.awt.event.ActionEvent evt) {
RefGen.generate();
String refNo = RefGen.reference();
clientLabel.setText(refNo);
}
The program generates the reference number but never increments the label value in InGenUI.java or the actually array itself in RefGen.java. It also seems that the array only holds a single value on each button click.
I think that refList stores the original refNo value generated but empties the array each time it does so. I suspect that each time I click genButton I am actually creating a new instance of refList and hence wiping out the old values. Is this correct? If so, how can I protect the instance of refList I created while keeping it in the RefGen.java class?
Thank you in advance.
ArrayList
but if it's big enough it makes a great difference checking if it contains each element. – Eypros Jul 29 at 10:02