3

All Java Collections implement Iterable, so they must provide an Iterator, which specifies an optional method remove(). When remove() is called on the Iterator, it can throw an UnsupportedOperationException.

How do I know whether a Collection in the Java standard library will return an Iterator that supports remove() or not without running code?

Of course I expected this information to be in the Javadoc of the remove() method of the class, but instead found a bunch of links to superclasses and interfaces. For example: http://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html#iterator-- I did not find any clarification following up on the links, either.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Aprel
  • 484
  • 1
  • 5
  • 10
  • The only real way is to try and handle the exception, I know crappy. The Collections API is not the most elegantly design API, it should have none mutable and mutable versions of most of the core interfaces – MadProgrammer Feb 07 '15 at 07:53
  • If you read the class-level documentation for TreeSet that you link to, it implies that remove() does in fact work. Would be nice to see some example code... – Mad Physicist Feb 07 '15 at 07:53
  • Your best bet is to read the javadoc. For example `Arrays.asList` says that the returned list has a fixed size so you can imagine that its iterator can't remove. Most "standard" collections are mutable and allow removal. – assylias Feb 07 '15 at 07:58
  • Is this a genuine problem? Are you really writing code that has to deal with Iterators of multiple kinds, which may or may not support removal? – user207421 Feb 07 '15 at 09:05

2 Answers2

4

There is no way of knowing this ex-ante. Unless it's properly documented that remove() is or isn't supported (and frankly, even if it is "properly" documented), your only way to know for sure is to try.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

The choice of a data structure is made on what you intend it to support so by the time you get to using it, you as a developer would already know if the underlying implementation supports removal or not.

An exception will be thrown if the actual implementation isn't in line with your assumption/ understanding.

Scorpion
  • 3,938
  • 24
  • 37