爲了代碼簡潔有時咱們會使用一些框架提供的工具類。如html
import org.apache.commons.collections.ListUtils; package java.util.Collections; List<String> strList = ListUtils.EMPTY_LIST; List<String> strList1 = Collections.emptyList();
實際該空List是個內部類,沒有實現add等方法,使用時會報錯。java
/** * {@inheritDoc} * * <p>This implementation always throws an * {@code UnsupportedOperationException}. * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { throw new UnsupportedOperationException(); }
又如,使用apache
arrays.aslist(T...a)
再進行add操做,一樣會報該錯。
https://www.2cto.com/kf/201806/751606.html框架
所以,仍是老老實實使用下面方式初始化List工具
List<String> strList=new ArrayList<>();
或者確認工具類提供的是java的ArrayList再使用。code