0

The following code should work, since join accepts an iterator as argument:

import static org.apache.commons.lang.StringUtils.join;
import java.text.StringCharacterIterator;

…

join(new StringCharacterIterator("A String"), " ");

Alas, it doesn’t. Can somebody explain to me why?

flying sheep
  • 8,475
  • 5
  • 56
  • 73

2 Answers2

1

According to the documentation, StringCharacterIterator inherits from and only from CharacterIterator. A CharacterIterator does not inherit from a generic Iterator, which is what join wants.

http://download.oracle.com/javase/1.4.2/docs/api/java/text/CharacterIterator.html

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
  • so the answer is that the Java standard library is a mess. So i need [this](http://stackoverflow.com/questions/3925130/java-how-to-get-iteratorcharacter-from-string) – flying sheep Feb 16 '11 at 13:07
  • @flying sheep: Partly, yes. When you deal with cross-libraries, like Oracle/Java with Apache, it gets even messier. – Evan Mulawski Feb 16 '11 at 13:08
  • No. The fact that it ends with Iterator doesn't mean it must have the same interface. A HashTable doesn't have much in common with a WoodenTable. – JB Nizet Feb 16 '11 at 13:10
  • 1
    I don’t want to argue about this. “`Iterator`” is an unambiguous term in most programming languages (one of which being Java). You just don’t call something an iterator if it doesn’t implement the builtin interface of the same name. – flying sheep Feb 16 '11 at 13:25
  • @flying sheep Actually if you look at the javadoc for the Iterator class it talks explicitly about a collection (which an array is not, or there wouldn't be the utility method to convert it to a collection). Also a String is a character array, which as is shown is not a collection in Oracle land. My guess is it is called `StringCharacterIterator` because `CharacterArrayTraversalAgent` didn't sound as nice. – Woot4Moo Feb 16 '11 at 14:05
  • when did java ever care about niceness? it is an inconsitent grown-into-a-thicket kind of language and library. and there are much worse names in there than `CharacterArrayTraversalAgent`. – flying sheep Feb 16 '11 at 21:46
0

First of all, the join method takes two arguments : an iterator and a separator string or char.

And if you look at the javadoc of StringCharacterIterator, you'll see that this class does not implement java.util.Iterator.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255