• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to use remove() method on an ArrayList  RSS feed

 
Robin Sharma
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

I get the UnsupportedOperationException exception when i try to run this code:


Please help.

DW
[ December 07, 2005: Message edited by: Jim Yingst ]
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are a couple of nasties that you are observing here. First, arrays are fixed length, therefore, the List returned by Arrays.asList will throw an UnsupportedOperationException if a "resizing" operation is invoked (such as remove). That this behaviour is not clearly documented is a limitation of the API Specification.

Most importantly, that you can even invoke such an operation is a horrible flaw that is intrinsic to the List interface. In fact, I became so annoyed at having to put up with this and many other flaws of Java 2 Collections, that I set about writing them "more correctly" (within the confines of the broken language).

For your case, I'd use:
http://www.contractualj.com/api/net/tmorris/adt/sequence/ArraySequence.html
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you call Arrays.asList(), it will return a List object which is really only a wrapper around the array. The List will be read-only. You can't insert or remove items into that list.

To make it work, create a new ArrayList object (which is a real, modifiable implementation of List) to which you pass the List returned by Arrays.asList():
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Jesper]: When you call Arrays.asList(), it will return a List object which is really only a wrapper around the array. The List will be read-only.

It's not actually read-only. As Tony notes, you can't use operations which change the length, such as add() or remove(). But you can use set().
[ December 07, 2005: Message edited by: Jim Yingst ]
 
Robin Sharma
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jesper de Jong:
When you call Arrays.asList(), it will return a List object which is really only a wrapper around the array. The List will be read-only. You can't insert or remove items into that list.

To make it work, create a new ArrayList object (which is a real, modifiable implementation of List) to which you pass the List returned by Arrays.asList():


Thanks Jesper. Your solution is working fine.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!