Note: this is my way of doing it because I'm not privy to lists. If there's a list that behaves in a way to complete this problem without an algorithm, great. Don't downvote my answer just because it's unnecessary.
I suppose you could have an ArrayList and just add IDs from it and always take the lowest one available.
So for example:
static ArrayList<Integer> ids = new ArrayList<Integer>();
public static void assignId() {
boolean foundId = false;
for (int i = 0; i < ids.size(); i++) {
if (ids.get(i) < 0) { // if it's negative, it was removed before
// make object ID to be i+1
ids.set(i, i+1); // and add it to the list
foundId = true;
break;
}
}
if (!foundId) { // can't find ID mid list to fill in
ids.add(ids.size()+1); // so give it a brand new one
}
}
public static void removeId(int id) {
ids.set(id-1, -1); // negative value means it was removed
}
So what I've done is create a list that has positive values for IDs, and negative values in places where there used to be an id, but isn't anymore. The reason for this is so that if the value in the list is negative, we can just replace it. For example:
// assign five IDs (1 through 5)
assignId();
assignId();
assignId();
assignId();
assignId();
// print ids for testing
for (int id : ids) {
System.out.print(id + ", ");
}
// outputs 1, 2, 3, 4, 5,
// now remove the id 3
removeId(3);
removeId(2);
// print ids for testing
for (int id : ids) {
System.out.print(id + ", ");
}
// outputs 1, 2, -1, 4, 5,
assignId(); // give this new object a new id (should be 2 replacing -1)
// print ids for testing
for (int id : ids) {
System.out.print(id + ", ");
}
// outputs 1, 2, -1, 4, 5,
assignId(); // give this new object a new id (should be 3 replacing -1)
// print ids for testing
for (int id : ids) {
System.out.print(id + ", ");
}
// outputs 1, 2, 3, 4, 5,
assignId(); // give this new object a new id (should a brand new ID)
// print ids for testing
for (int id : ids) {
System.out.print(id + ", ");
}
// outputs 1, 2, 3, 4, 5, 6,