1. /*
  2. * Copyright 1999-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.apache.commons.collections.iterators;
  17. import java.util.Iterator;
  18. import org.apache.commons.collections.Unmodifiable;
  19. /**
  20. * Decorates an iterator such that it cannot be modified.
  21. *
  22. * @since Commons Collections 3.0
  23. * @version $Revision: 1.5 $ $Date: 2004/02/18 00:59:50 $
  24. *
  25. * @author Stephen Colebourne
  26. */
  27. public final class UnmodifiableIterator implements Iterator, Unmodifiable {
  28. /** The iterator being decorated */
  29. private Iterator iterator;
  30. //-----------------------------------------------------------------------
  31. /**
  32. * Decorates the specified iterator such that it cannot be modified.
  33. * <p>
  34. * If the iterator is already unmodifiable it is returned directly.
  35. *
  36. * @param iterator the iterator to decorate
  37. * @throws IllegalArgumentException if the iterator is null
  38. */
  39. public static Iterator decorate(Iterator iterator) {
  40. if (iterator == null) {
  41. throw new IllegalArgumentException("Iterator must not be null");
  42. }
  43. if (iterator instanceof Unmodifiable) {
  44. return iterator;
  45. }
  46. return new UnmodifiableIterator(iterator);
  47. }
  48. //-----------------------------------------------------------------------
  49. /**
  50. * Constructor.
  51. *
  52. * @param iterator the iterator to decorate
  53. */
  54. private UnmodifiableIterator(Iterator iterator) {
  55. super();
  56. this.iterator = iterator;
  57. }
  58. //-----------------------------------------------------------------------
  59. public boolean hasNext() {
  60. return iterator.hasNext();
  61. }
  62. public Object next() {
  63. return iterator.next();
  64. }
  65. public void remove() {
  66. throw new UnsupportedOperationException("remove() is not supported");
  67. }
  68. }