The "best" way to do this in an effective way would be to :
List<MyClass> list = new ArrayList<MyClass>();
list.add(new MyClass("name", "address", 23));
list.add(new MyClass("name2", "address2", 45));
although it requires a lot of typing but as you can clearly see this is more efficient
Another alternative would be to use google guava (not tested for efficiency):
ArrayList<MyClass> list = new ArrayList<MyClass>(
new MyClass("name", "address", 23),
new MyClass("name2", "address2", 45) );
The required import is import static com.google.common.collect.Lists.newArrayList;
also, you can use double braces initialization as originally proposed by @Rohit Jain: -
List<MyClass> list = new ArrayList<MyClass>() {
{
add(new MyClass("name", "address", 23));
add(new MyClass("name2", "address2", 45));
}
};
As you can see that, inner braces
is just like an initializer
block, which is used to initialize the list
in one go..
note the semi-colon at the end of your double-braces
also note the last method has some downsides as discussed here.