Hello,
I need to create 20 objects of Class B, using while loop in class A. In class B i have a variable that should increment each time an object is created, how i should build class B's cunstractor so each time that variable increase and not become zero?
1 reply to this topic
#1
Posted 31 May 2011 - 03:09 AM
"Programming is like sex. One mistake and you have to support it for the rest of your life."
-Michael Sinz|
|
|
#2
Posted 31 May 2011 - 05:12 AM
You'd use a static value, and increment that. Remember that this could cause problems with multithreading, so I suggest you use the AtomicInteger object instead of just a raw int.
import java.util.concurrent.atomic.AtomicInteger;
public class SomeClass
{
private static AtomicInteger counter = new AtomicInteger();
public SomeClass()
{
int objectNum = counter.getAndIncrement();
// Do whatever it is you do.
}
}
Wow I changed my sig!
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account


Back to top









