简体   繁体   中英

Get a static java method to return highest variable value

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++;
    }
}

You pretty well answered the question yourself. Since your nextID variable is ever increasing each time an object is created, any time you grab the value of that variable, it is always the highest. All you need, as you've said, is to create a static method that returns the current value of nextID . Simply:

public static int getNextID(){
    return nextID;
}

Figured it out!

Public static int highestID() {

   return nextID;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM