Reputation: 203
Is this a good java practice(in terms of memory and computational efficiency in terms of time) to associate a static list of objects in the class itself.
package collection;
/**
* Created by ANJANEY on 5/28/2014.
*/
import java.util.*;
class Student1
{
int rollId;
String name;
static List<Student1> studentList=new ArrayList<Student1>();
Student1(int rollId,String name)
{
this.rollId=rollId;
this.name=name;
studentList.add(this);
}
}
public class A {
public static void main(String aaaa[])
{
new Student1(1,"Anjaney");
new Student1(2,"Prerak");
Iterator<Student1> itr=Student1.studentList.iterator();
while(itr.hasNext())
{
Student1 st=itr.next();
System.out.println("Roll = "+st.rollId+" Name = "+st.name);
}
}
}
Upvotes: 7
Views: 2570
Reputation: 4360
Since the list is static it would anyways be initialized only once for a single class, so declaring the list outside the class (for example in a main method) would not make much difference since even there it would be initialized only once. But declaring the list inside the class and initializing it (using constructors or getter/setter), will definitely give more control over access of the list object.
Upvotes: 0
Reputation: 53535
What you implemented here is called "instance controlled" class (See Effective Java - Joshua Bloch Chapter 2 - Item I).
Usually developers implement instance-controlled class using a static factory, you can keep reference to the objects that were created (like you're doing with that List) as well as do other stuff such as restrict the number of instances. A famous private case of an "instance controlled" class is called Singleton (though in that case there's no point in keeping a list...).
From performance perspective I don't see any meaningful gain/loss between keeping the list inside the class or outside of it.
Upvotes: 3