Fixed Sized Vs Constant(final) Collection in Java

This is very important to understand the difference between two version of creating collection in Java-

  1. final List list1 = new ArrayList();
  2. List list2 =  Arrays.asList(…);


Here in 1 type making list as final I am making collection final collection which mean I can not change its reference, but I can add/remove elements in list1.

final List list1= new ArrayList();
list1 = new ArrayList<>(); The final local variable list1 cannot be assigned.

In list2 adding/removing elements is not allowed and throw runtime exception java.lang.UnsupportedOperationException

List list2 = Arrays.asList(1,2,3,3);
list2.add(1); // java.lang.UnsupportedOperationException

Hope this article helps you to understand the difference between final collection and fixed sized collection version. Use them wisely.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *