title: Safely traversing a raw Iterator in Java?
body: <p>I'm using a third party library that returns a raw Iterator, e.g.</p>
  
  <pre><code>Iterator&lt;?&gt; children = element.getChildElements();
  </code></pre>
  
  <p>I know the actual type, but I don't necessarily trust the third party lib to stick with it in the future.  There are two (that I can think of) somewhat <strong>risky</strong> ways to traverse this:</p>
  
  <pre><code>@SuppressWarnings("unchecked")
  Iterator&lt;ActualObject&gt; currentChildren = (Iterator&lt;ActualObject&gt;)currentElement.getChildElements();
  </code></pre>
  
  <p>or</p>
  
  <pre><code>Iterator&lt;?&gt; children = element.getChildElements();
  while (null != children &amp;&amp; children.hasNext()) {
    ActualObject child = (ActualObject)children.next(); //Possible ClassCastException @ runtime
    ...
  }
  </code></pre>
  
  <p>The only "safe" way I could come up with to traverse this sort of iterator is the following:</p>
  
  <pre><code>Iterator&lt;?&gt; children = element.getChildElements();
  while (null != children &amp;&amp; children.hasNext()) {
    Object obj = children.next();
    ActualObject child = null;
      if (obj instanceof ActualObject)
        child = (ActualObject)obj;
      ...
  }
  </code></pre>
  
  <p><strong>This seems overly verbose. Is there a better, yet equally "safe" way to traverse a raw iterator?</strong></p>
  
  <p>EDIT: I realize I can catch/log the exception in an else block, I was looking (hoping) for a Java language equivalent of what ColinD has mentioned below.</p>