001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * https://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.collections4.iterators; 018 019import java.util.Iterator; 020import java.util.NoSuchElementException; 021import java.util.Objects; 022 023import org.w3c.dom.Node; 024import org.w3c.dom.NodeList; 025 026/** 027 * An {@link Iterator} over a {@link NodeList}. 028 * <p> 029 * This iterator does not support {@link #remove()} as a {@link NodeList} does not support 030 * removal of items. 031 * </p> 032 * 033 * @since 4.0 034 * @see NodeList 035 */ 036public class NodeListIterator implements Iterator<Node> { 037 038 /** The original NodeList instance */ 039 private final NodeList nodeList; 040 041 /** The current iterator index */ 042 private int index; 043 044 /** 045 * Convenience constructor, which creates a new NodeListIterator from 046 * the specified node's childNodes. 047 * 048 * @param node Node, whose child nodes are wrapped by this class. Must not be null 049 * @throws NullPointerException if node is null 050 */ 051 public NodeListIterator(final Node node) { 052 Objects.requireNonNull(node, "node"); 053 this.nodeList = node.getChildNodes(); 054 } 055 056 /** 057 * Constructor, that creates a new NodeListIterator from the specified 058 * {@code org.w3c.NodeList} 059 * 060 * @param nodeList node list, which is wrapped by this class. Must not be null 061 * @throws NullPointerException if nodeList is null 062 */ 063 public NodeListIterator(final NodeList nodeList) { 064 this.nodeList = Objects.requireNonNull(nodeList, "nodeList"); 065 } 066 067 @Override 068 public boolean hasNext() { 069 return nodeList != null && index < nodeList.getLength(); 070 } 071 072 @Override 073 public Node next() { 074 if (nodeList != null && index < nodeList.getLength()) { 075 return nodeList.item(index++); 076 } 077 throw new NoSuchElementException("underlying nodeList has no more elements"); 078 } 079 080 /** 081 * Always throws {@link UnsupportedOperationException}. 082 * 083 * @throws UnsupportedOperationException Always thrown. 084 */ 085 @Override 086 public void remove() { 087 throw new UnsupportedOperationException("remove() method not supported for a NodeListIterator."); 088 } 089}