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 *      http://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.Objects;
021
022import org.apache.commons.collections4.Unmodifiable;
023
024/**
025 * Decorates an iterator such that it cannot be modified.
026 * <p>
027 * Attempts to modify it will result in an UnsupportedOperationException.
028 * </p>
029 *
030 * @param <E> the type of elements returned by this iterator.
031 * @since 3.0
032 */
033public final class UnmodifiableIterator<E> implements Iterator<E>, Unmodifiable {
034
035    /**
036     * Decorates the specified iterator such that it cannot be modified.
037     * <p>
038     * If the iterator is already unmodifiable it is returned directly.
039     *
040     * @param <E>  the element type
041     * @param iterator  the iterator to decorate
042     * @return a new unmodifiable iterator
043     * @throws NullPointerException if the iterator is null
044     */
045    public static <E> Iterator<E> unmodifiableIterator(final Iterator<? extends E> iterator) {
046        Objects.requireNonNull(iterator, "iterator");
047        if (iterator instanceof Unmodifiable) {
048            @SuppressWarnings("unchecked") // safe to upcast
049            final Iterator<E> tmpIterator = (Iterator<E>) iterator;
050            return tmpIterator;
051        }
052        return new UnmodifiableIterator<>(iterator);
053    }
054
055    /** The iterator being decorated */
056    private final Iterator<? extends E> iterator;
057
058    /**
059     * Constructs a new instance.
060     *
061     * @param iterator  the iterator to decorate
062     */
063    private UnmodifiableIterator(final Iterator<? extends E> iterator) {
064        this.iterator = iterator;
065    }
066
067    @Override
068    public boolean hasNext() {
069        return iterator.hasNext();
070    }
071
072    @Override
073    public E next() {
074        return iterator.next();
075    }
076
077    @Override
078    public void remove() {
079        throw new UnsupportedOperationException("remove() is not supported");
080    }
081
082}