Arrays.asList () stepped pit

      When using iterators implement delete a collection of elements encountered a problem

 1 public static void main(String[] args) {
 2         String[] ss = {"sys","admin","visa","bude"};
 3         List<String> list = Arrays.asList(ss);
 4        9         Iterator it = list.iterator();
10         while(it.hasNext()){
11             Object obj = it.next();
12             if("visa".equals(obj)){
13                 it.remove();
14             }
15         }
16         System.out.println(list);
17     }

    Running the above piece of code found in 13 lines, remove elements when an exception is thrown UnsupportedOperationException, does not support the operation.

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.remove(AbstractList.java:144)
    at Test3.main(Test3.java:13)

    So, I created a new collection, instead of converting the array into a collection

 1 public static void main(String[] args) {
 2         String[] ss = {"sys","admin","visa","bude"};
 3 //        List<String> list = Arrays.asList(ss);
 4         List<String> list = new ArrayList<String>();
 5         list.add("sys");
 6         list.add("admin");
 7         list.add("visa");
 8         list.add("bude");
 9         Iterator it = list.iterator();
10         while(it.hasNext()){
11             Object obj = it.next();
12             if("visa".equals(obj)){
13                 it.remove();
14             }
15         }
16         System.out.println(list);
17     }

Normal operating results

[Sys admin will]

  Opening the Arrays.asList () source code found, asList () This method returns an Array $ ArrayList object, and then new ArrayList <String> () returns a java.util.ArrayList object.

  Array $ ArrayList and ArrayList inherit AbstractList class, but Array $ ArrayList does not override the remove method of the parent class, ArrayList overrides the remove method. So, by the array transformed into a collection not implement the remove operation, in addition Array $ ArrayList did not add operations.

 

Solution: java.util.ArrayList in the list and then placed on the line.

 1 public static void main(String[] args) {
 2         String[] ss = {"sys","admin","visa","bude"};
 3         List<String> list1 = Arrays.asList(ss);
 4         List<String> list = new ArrayList<String>(list1);
 5         Iterator it = list.iterator();
 6         while(it.hasNext()){
 7             Object obj = it.next();
 8             if("visa".equals(obj)){
 9                 it.remove();
10             }
11         }
12         System.out.println(list);
13     }

operation result

[Sys admin will]

  

 

Guess you like

Origin www.cnblogs.com/CSC20190701/p/11118419.html