Re: static field initialised twice
Omega wrote:
I have a problem with static field in my class.
I want every object of may class to have unique id, so I do something
like this:
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.
No it doesn't. Adding a toString to your class A (so we can see what's
happening):
@Override
public String toString() {
return "A with id " + id;
}
Then testing it with:
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
A a3 = new A();
System.out.println(a1);
System.out.println(a2);
System.out.println(a3);
}
You get:
A with id 1
A with id 2
A with id 3
Exactly as you should.
I notices that it happens in very starnge situation.
I have class like this:
class B {
ArrayList<A> list;
public class B{
list = new ArrayList<A>();
}
}
A strange class indeed, B with a nested class also called B! I think
you've gotten a constructor mixed up with an inner class.
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.
No it doesn't. Fixing that constructor:
import java.util.ArrayList;
class B {
ArrayList<A> list;
public B() {
list = new ArrayList<A>();
}
}
And modifying out test to:
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
B b1 = new B();
A a3 = new A();
System.out.println(a1);
System.out.println(a2);
System.out.println(a3);
}
We still get:
A with id 1
A with id 2
A with id 3
So the sequence is not affected.
Thanks in advance
Omega
How are you getting your wrong impressions of the values? - you don't
show any output, or say how (you think) you know what's going on.
Mark