Reputation: 1654
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();
}
}
Upvotes: 3
Views: 18488
Reputation: 1581
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.
Upvotes: 13
Reputation: 2598
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.
Upvotes: 6
Reputation: 119
Make your teamId variable static & initialize it with some integer value (recommended is -1).
Using initial value -1 cause first teamId = 0.
Upvotes: -2