Diofloyk Diofloyk - 3 months ago 12
Java Question

Interface List method add(int index, E element); Why i have UnsupportedOperationEception?

I'm make unit test Interface List. Simple code but i can't understand, why

testAdd()
throws UnsupportedOperationException but
testSet()
do not throws this exception.

public class testList {
private static List<Integer> testList = new ArrayList<>();

public static void main(String[] args) {
init();
testGet();
testSet();
testAdd();
}

private static void init() {
testList = Arrays.asList(0, 1, 2, 3, 1, 2, 5, 4);
}

private static void testGet() {
assertEquals(Integer.valueOf(2), testList.get(2));
}

private static void testSet() {
testList.set(6, 5);
assertEquals(new Integer[]{0, 1, 2, 3, 1, 2, 5, 4}, testList.toArray());
}

private static void testAdd() {
testList.add(0, 1);
assertEquals(new Integer[]{1, 0, 2, 2, 3, 3, 4, 5, 4}, testList.toArray());
}
}


This is from AbstractList

enter image description here

Answer
Arrays.asList

Returns an wrapper to the original list, so you will not be able to change the list length (add() or remove()).

Comments