有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中字符串数组到数组列表的问题

我在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) 个答案

  1. # 1 楼答案

    正如您在source off ArrayList中看到的,不支持删除方法:

     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: 
    

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

  2. # 2 楼答案

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

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