Obtain a static java method to return the highest variable value

advertisements

In my program I declared a static variable:

private static int nextID = 0;

Which is used in my constructor

Vehicle() {

  idNum = nextID++

 }

Basically, what this is doing is ensuring that every time I make a new Vehicle object, it will have a unique identification number. Now I want to make a static method that would return the highest IDnumber used so far. How would I do that?


You can just return the current value of nextID...

Note however that your class is not thread safe. In other words if there are two different objects created at the same time they can both get the same "unique" id. In order to prevent this you need some sort of locking.

private static int nextID = 0;
private static Object lockObj = new Object();

public static int highestID()
{
    synchronized(lockObj)
    {
        return nextID-1;
    }
}

public Vehicle() {
    synchronized(lockObj)
    {
        idNum = nextID++;
    }
}