java - Add elements in ArrayList in more readable way -
i have below code snippet add elements in arraylist
list <integer> mylist = new arraylist(); mylist.add(1); mylist.add(2); mylist.add(3); mylist.add(4);
i looking more readable , elegant way add elements in arraylist
, below. know below not allowed there other readable/elegant way?
mylist.add(1).add(2).add(3).add(4)
update:- on java 1.6
when know elements prior instantiating:
list<integer> mylist = new arraylist<>(arrays.aslist(1, 2, 3, 4));
or if want add them existing list:
list<integer> mylist = new arraylist<>(); // stuff mylist.addall(arrays.aslist(1, 2, 3, 4));
to make more readable, can
import static java.util.arrays.aslist;
and use
list<integer> mylist = new arraylist<>(aslist(1, 2, 3, 4));
or
list<integer> mylist = new arraylist<>(); // stuff mylist.addall(aslist(1, 2, 3, 4));
in case know never ever want add more elements list, can write
list<integer> mylist = arrays.aslist(1, 2, 3, 4);
or static import:
list<integer> mylist = aslist(1, 2, 3, 4);
Comments
Post a Comment