public class MyListConstant
{
public static final
List CONSTANT = Collections.unmodifiableList(getConstant());
private static List
getConstant() {
List constant1 = new
ArrayList();
constant1.add("a");
constant1.add("b");
constant1.add("c");
constant1.add("d");
return constant1;
}
}
Note:
- It is better to use Array constants
instead of list constants.
- List constant need to be created with unmodifiableList
method otherwise it will modified with its set method.
CONSTANT.set(1,
"replaced");
Arrays.asList method returns a List which can not be changed. If you try to add/remove an element then it will throw java.lang.UnsupportedOperationException.
ReplyDeleteSo it is already constant. no need to mention "final".
yes, but you can assign object to CONSTANT if it is not final and List created by Arrays.asList can be modified by using set method.
Delete