Reputation: 1107
I want to set List
object as a class field and then use ArrayList()
as a concrete class of List
.
The reason is that I want to call setData
method many times in different parts of program and every time it must add data to the same object data, not different ones.
Here is the code:
import java.util.ArrayList;
import java.util.List;
public class container {
private static List<String> data = ArrayList<String>();
public static List<String> getData() {
return data;
}
public static void setData(String a) {
data.add(a);
}
}
I guess this code should cause error.
How can I change the code so that it has the similar result with correct syntax?
If this code will not cause errors can anyone tell me when(at what part of execution program) will be static data object created? P.S. I am not going to create container object,just want to call container.setData(String a) method many times in program.
Upvotes: 0
Views: 271
Reputation: 2878
Your code works if you add the missing new
word and it will work as you want. The ArrayList will be instantiated when the container
class is loaded. This usually happens when the control flow reaches a class that references this class. So whenever you call any of these methods the data field will already be ready.
However you may want to learn the 'singleton design pattern' and you may want to synchronize the access to the shared object if you create several threads (or you use a library that do that for you).
import java.util.ArrayList;
import java.util.List;
public class container {
private static List<String> data = new ArrayList<String>(); // <-- new was missing
public static List<String> getData() {
return data;
}
public static void setData(String a) {
data.add(a);
}
}
Upvotes: 1
Reputation: 1538
I cite: "The reason is that I want to call setData method many times in different parts of program and every time it must add data to the same object data, not different ones."
If your data field is declared as static
, there will only be one data field, so this should not pose any problems. Have you tested the code, or do you just think there will be errors?
Upvotes: 1
Reputation: 4462
Test below:
import java.util.ArrayList;
import java.util.List;
public class container {
private static List<String> data = new ArrayList<String>();
// for java 1.5-1.6 point type here ^^^^^^^
// for java 1.7+ you can use new ArrayList<>();
public static List<String> getData() { return data;}
public static void setData(String a) { data.add(a);}
}
Upvotes: 1