Re: static field initialised twice
Omega wrote:
class A {
private int id;
private static int sequence = 1;
public A () {
id = sequence;
sequence++;
}
}
Everythings is fine with the first object, it has id == 1, but when I
create second one, it has id == 0.
I notices that it happens in very starnge situation.
It makes it very difficult to find the cause of a problem if you haven't
posted the problem code. As you don't know where the problem is, it is
generally best to post a short, compilable piece of code that
demonstrates the problem. (And make sure you have compiled all the class
files from scratch, so that there cannot be any old versions hanging about.)
class B {
ArrayList<A> list;
public class B{
list = new ArrayList<A>();
}
}
I noticed that sequence changes value to 0 when I create new object of
class B. Why is it like this, and what can I do to stop it from
happening.
I can't reproduce the problem. Here's my modified, compilable version of
your code. Do you get the same thing?
import java.util.ArrayList;
class A {
private int id;
private static int sequence = 1;
public A () {
id = sequence;
sequence++;
}
public int getID() {
return id;
}
}
class B {
ArrayList<A> list;
//public class B{
public B() {
list = new ArrayList<A>();
}
}
class Driver {
public static void main(String[] args) {
A a1 = new A();
B bo = new B();
//B bi = bo.new B.B();
A a2 = new A();
System.err.println(a1.getID());
System.err.println(a2.getID());
}
}
Note that A.sequence is not correctly synchronised. Either put it in a
synchronised block (probably synchronised against A.class, or a static
lock field), or from 1.5 use java.util.concurrent.atomic.AtomicInteger.
Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/