001 /* 002 * LAPIS lightweight structured text processing system 003 * 004 * Copyright (C) 2003 Massachusetts Institute of Technology. 005 * All rights reserved. 006 * 007 * This library is free software; you can redistribute it 008 * and/or modify it under the terms of the GNU General 009 * Public License as published by the Free Software 010 * Foundation, version 2. 011 * 012 * LAPIS homepage: http://graphics.lcs.mit.edu/lapis/ 013 */ 014 015 package lapisx.iterator; 016 017 import java.util.*; 018 019 /** 020 * Concatenates two or more Iterators. 021 */ 022 public class ConcatIterator implements Iterator { 023 Iterator g; 024 Iterator otherIterators; 025 026 private static Iterator EMPTY = Collections.EMPTY_LIST.iterator (); 027 028 /** 029 * Make a concatenation of two iterators. 030 * @param g1 First iterator 031 * @param g2 Second iterator 032 */ 033 public ConcatIterator (Iterator g1, Iterator g2) { 034 g = g1; 035 otherIterators = Collections.singleton (g2).iterator (); 036 } 037 038 /** 039 * Make a concatenation of a collection of iterators. 040 * @param iterators collection of iterators to concatenate 041 * @throws ClassCastException if the first element of iterators doesn't implement Iterator 042 */ 043 public ConcatIterator (Collection iterators) { 044 otherIterators = iterators.iterator (); 045 if (otherIterators.hasNext ()) 046 g = (Iterator) otherIterators.next (); 047 else 048 g = EMPTY; 049 } 050 051 public boolean hasNext() { 052 if (g.hasNext ()) 053 return true; 054 while (otherIterators.hasNext ()) { 055 g = (Iterator) otherIterators.next (); 056 if (g.hasNext ()) 057 return true; 058 } 059 return false; 060 } 061 062 public Object next() { 063 while (true) { 064 try { 065 return g.next(); 066 } catch (NoSuchElementException e) { 067 if (otherIterators.hasNext ()) 068 g = (Iterator) otherIterators.next (); 069 else 070 throw e; 071 } 072 } 073 } 074 075 public void remove () { 076 g.remove (); 077 } 078 }