字符串数组到java中的Array List问题

时间:2015-08-04 07:02:12

标签: java arrays arraylist

我在java collection util中面临一些问题,基本上我在arrayList上使用 removeall()打破了这些步骤,但它抛出 java.lang.UnsupportedOperationException 当我在单行中进行时,它按预期正常工作。因此,当我分几个步骤打破它时,我不明白这个问题是什么。代码是

public class Test4 {

public static void main(String args[]){
    String unInstall="com.mobikwik_new,com.cleanmaster.mguard,com.htc.flashlight,com.mobilemotion.dubsmash";
    String  install="com.mobikwik_new,com.cleanmaster.mguard,com.htc.flashlight";
    List<String> installList = new ArrayList<String>();
    List<String> unInstallList = new ArrayList<String>();
    String inL[] = install.split(",");
    String UnInL[] = unInstall.split(",");
    installList = Arrays.asList(inL);
    unInstallList = Arrays.asList(UnInL);
    unInstallList.remove(installList);
    //List<String> installList = new ArrayList<>(Arrays.asList(install.split(",")));
    //List<String> unInstallList = new ArrayList<>(Arrays.asList(unInstall.split(",")));

    unInstallList.removeAll(installList);

    System.out.println("unInstall : "+unInstallList);
}
}

注意:当我只使用评论行代替上述所有步骤时,其工作正常

抛出的例外是 -

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(Unknown Source)
at java.util.AbstractList$Itr.remove(Unknown Source)
at java.util.AbstractCollection.removeAll(Unknown Source)
at Test4.main(Test4.java:21)

谢谢!

2 个答案:

答案 0 :(得分:5)

Arrays.asList返回一个固定大小的列表,因为它由作为参数给出的数组支持。返回的列表不支持remove操作,正如您所看到的错误消息所示。

如果要从列表中删除某些内容,请将返回的列表包装在ArrayListnew ArrayList<>(Arrays.asList(inL));中。

答案 1 :(得分:1)

正如你在sourceList中看到的那样,不支持删除方法:

 616:   /**
 617:    * Remove the element at a given position in this list (optional operation).
 618:    * Shifts all remaining elements to the left to fill the gap. This
 619:    * implementation always throws an UnsupportedOperationException.
 620:    * If you want fail-fast iterators, be sure to increment modCount when
 621:    * overriding this.
 622:    *
 623:    * @param index the position within the list of the object to remove
 624:    * @return the object that was removed
 625:    * @throws UnsupportedOperationException if this list does not support the
 626:    *         remove operation
 627:    * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
 628:    * @see #modCount
 629:    */
 630:   public E remove(int index)
 631:   {
 632:     throw new UnsupportedOperationException();
 633:   }
 634: 

因此,您无法使用此方法删除元素。