i have MyClass as
MyClass(String, String, int);
i know about how to add to add to ArrayList in this way:
MyClass.name = \"N
The "best" way to do this in an effective way would be to :
List list = new ArrayList();
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 list = new ArrayList(
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 list = new ArrayList() {
{
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.