Sunday, November 14, 2010

Java : Best way to declare a static list constant


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:
  1. It is better to use Array constants instead of list constants.
  2. List constant need to be created with unmodifiableList method otherwise it will modified with its set method.
CONSTANT.set(1, "replaced");

2 comments:

  1. 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.

    So it is already constant. no need to mention "final".

    ReplyDelete
    Replies
    1. 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