1

While running following code, UnsupportedOperationException is thrown at .remove() method.

By this code:

List list = Array.asList(array) ;
list.remove(0);
assylias
  • 321,522
  • 82
  • 660
  • 783
Gary
  • 475
  • 1
  • 4
  • 4
  • 3
    Indeed. What is your question? – Ismail Badawi Jun 19 '13 at 07:02
  • The first thing you should do every time you have a question about Java is read the documentation. In this case, you would google ["_java 7 Arrays_"](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html) and look for the _asList()_ method. The answer to most questions is in the first sentence. – jahroy Jun 19 '13 at 07:15

2 Answers2

10

Arrays#asList:

Returns a fixed-size list backed by the specified array

Thus, You can't add/remove elements to/from it.

To overcome this problem, you can do:

List modifiableList = new ArrayList(Arrays.asList(array));
Maroun
  • 94,125
  • 30
  • 188
  • 241
2

If you want to remove some Object from List of objects its quite analogical way to do it directly. You need to use Iterator.

List<Integer> l = new ArrayLIst<>(); // or List<Integer> l = new ArrayLIst<Integer>();
Iterator<Integer> iter = l.iterator();
while (iter.hasNext()) {
    if (iter.next().intValue() == 5) {
        iter.remove();
    }
}
Maroun
  • 94,125
  • 30
  • 188
  • 241
Lugaru
  • 1,430
  • 3
  • 25
  • 38