-1

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

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
diofloyk
  • 133
  • 1
  • 5

2 Answers2

1
Arrays.asList

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

McNultyyy
  • 992
  • 7
  • 12
  • You're completely right. I'll update my answer – McNultyyy Aug 24 '16 at 15:57
  • Also, please make a minimal effort to find duplicates before you attempt to answer questions. This one in particular has been asked and answered hundreds of times. Instead, flag (or vote once you have enough reputation) to close as such. – Sotirios Delimanolis Aug 24 '16 at 16:02
-2

Arrays.toList(T... t)retrun a java.util.Arrays.ArrayList not java.util.ArrayList

this class is a add methods is extends of AbstractList like this code

public void add(int index, E element) {
    throw new UnsupportedOperationException();
}

so throws a UnsupportedOperationException

lonecloud
  • 413
  • 3
  • 12