简体   繁体   中英

Auto-Increment id in java

Team one and Team two have both id 0? What am I doing wrong? I'm just trying to auto increment the id every time a new object is made.

This is code from Team.java

public class Team{
    private int teamId;

    public Team(){
        this.teamId= teamId++;
    }
    public void printTeamId(){
        System.out.println(this.teamId);
    }
}

This is code from Main.java

public class Main {

    public static void main(String[] args) {

    Team one= new Team();
    Team two= new Team();
        one.printTeamId();
        two.printTeamId();
    }
}

You need an extra static variable to store the amount of teams. static means that all the objects share this variable. Every team has it's own variable teamId , but share the variable teamIdCounter

public class Team{
    private int teamId;
    private static int teamIdCounter = 0;

    public Team(){
        this.teamId= teamIdCounter++;
    }
    public void printTeamId(){
        System.out.println(this.teamId);
    }
}

If you are using multiple threads, check the other answers on how to use AtomicInteger to count your objects threads-safe.

About the static variable is ok but if you want to be thread safe use Atomic Integer.

public class Team{
    private int teamId;
    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    public Team(){
        this.teamId= atomicInteger.incrementAndGet();
    }
    public void printTeamId(){
        System.out.println(this.teamId);
    }
}

This will make a thread safe counter instead a static counter that will not be thread safe.

Make your teamId variable static & initialize it with some integer value (recommended is -1).

Using initial value -1 cause first teamId = 0.

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