Reputation: 709
I have a class with an ArrayList
of pre-determined items, in this example fruits. In my code I have a constructor call a method that populates my list.
The problem is every time an instance of this class is instantiated, the list is repopulated. How can I create and populate the list once?
public class Test {
ArrayList<String> lst = new ArrayList<String>();
public Test() {
populate();
}
public void populate() {
lst.add("Apple");
lst.add("Banana");
}
}
Upvotes: 2
Views: 2320
Reputation: 100
have a look at the singleton pattern u get many simple informations form here: http://www.javaworld.com/article/2073352/core-java/simply-singleton.html
depending on this surce, i can try it once with your class:
public class TestClass {
private static TestClass instance = null;
ArrayList<String> lst = new ArrayList<String>();
protected TestClass () {
populate();
}
public static TestClass getInstance(){
if(instance == null)
instance = new TestClass();
return instance;
}
public void populate() {
lst.add("Apple");
lst.add("Banana");
}
}
so if u want to create OR get the class, run the getInstance() method and not the constructor (u even cant run the constructor cause it is protected) notice: i didnt test the code, but it looks fine, if there are any problems or further questions, i still can run it to fix them, just comment then or let me know if it works / solved your problem
Upvotes: 0
Reputation: 201447
You could make it static
, and use a static
initialization block. I would also prefer to program to the List
interface, and I would use a diamond operator <>
. Something like,
public class Test {
private static List<String> lst = new ArrayList<>();
static {
lst.add("Apple");
lst.add("Banana");
}
public Test() {
// ...
}
}
Or, use Arrays.asList(T...)
and eliminate the initalization block like
public class Test {
private static List<String> lst = Arrays.asList("Apple", "Banana");
public Test() {
// ...
}
}
Upvotes: 4
Reputation: 1388
you can create singleton class
public class MyClass{
private static MyClass instance;
private ArrayList<String> lst;
private MyClass(){
lst = new ArrayList<String>();
lst.add("Apple");
lst.add("Banana");
}
public static MyClass getInstance(){
if(instance == null){
instance = new MyClass();
}
return instance;
}
}
Upvotes: 1
Reputation: 2006
You can use static with static block.
public class Test {
static ArrayList<String> lst = new ArrayList<String>();
static {
populate();
}
public static void populate() {
lst.add("Apple");
lst.add("Banana");
}
}
It will call once while loading a class.
Upvotes: 1