2016-08-24 25 views
-1

我做單元測試接口列表。簡單的代碼,但我不明白,爲什麼testAdd()拋出UnsupportedOperationException但testSet()不會拋出此異常。接口列表方法add(int index,E元素);爲什麼我有UnsupportedOperationEception?

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()); 
    } 
} 

這是AbstractList的

enter image description here

+1

我只想指出'testAdd'應該失敗 –

+0

@ cricket_007是的,對不起,它只是測試的一部分:) – diofloyk

回答

1
Arrays.asList 

返回一個包裝到原來的列表,所以你將無法更改列表長度(add()remove())。

+0

你完全正確。我會更新我的答案 – McNultyyy

+0

另外,在嘗試回答問題之前,請盡最大努力找到重複的內容。特別是這個問題已被問及答覆數百次。相反,標誌(或者一旦你有足夠的聲望就可以投票)就這樣關閉。 –

-1

你知道在這個列表中,在這個列表中有一些元素,如果你想添加你可以使用add(value);在索引0中有一些索引0的值,如果你添加的話不支持 testList.add(0,1); 設置是否意味着如果你改變你的值就OK testList.set(6,5);

+1

最好在代碼塊之外提供一些文本來解釋你想顯示的內容 –

+0

對不起,我是一個sprog – lonecloud

相關問題