001/* Copyright (C) 2013 TU Dortmund 002 * This file is part of AutomataLib, http://www.automatalib.net/. 003 * 004 * AutomataLib is free software; you can redistribute it and/or 005 * modify it under the terms of the GNU Lesser General Public 006 * License version 3.0 as published by the Free Software Foundation. 007 * 008 * AutomataLib is distributed in the hope that it will be useful, 009 * but WITHOUT ANY WARRANTY; without even the implied warranty of 010 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 011 * Lesser General Public License for more details. 012 * 013 * You should have received a copy of the GNU Lesser General Public 014 * License along with AutomataLib; if not, see 015 * http://www.gnu.de/documents/lgpl.en.html. 016 */ 017package net.automatalib.commons.util; 018 019import java.util.BitSet; 020import java.util.Iterator; 021 022/** 023 * Iterator for iterating over a BitSet like over a normal collection. 024 * The type returned by next() is {@link Integer}. 025 * 026 * @author Malte Isberner <malte.isberner@gmail.com> 027 */ 028public class BitSetIterator implements Iterator<Integer> { 029 private final BitSet bitSet; 030 private int currBitIdx = 0; 031 032 /* 033 * Set currBitIdx to the next index which contains a 1-bit. 034 */ 035 private void findNextSetBit() { 036 while(currBitIdx < bitSet.size() && !bitSet.get(currBitIdx)) 037 currBitIdx++; 038 } 039 040 /** 041 * Constructor. 042 * @param bitSet the bitset over which to iterate. 043 */ 044 public BitSetIterator(BitSet bitSet) { 045 this.bitSet = bitSet; 046 findNextSetBit(); 047 } 048 049 /* 050 * (non-Javadoc) 051 * @see java.util.Iterator#hasNext() 052 */ 053 @Override 054 public boolean hasNext() { 055 return currBitIdx < bitSet.size(); 056 } 057 058 /* 059 * (non-Javadoc) 060 * @see java.util.Iterator#next() 061 */ 062 @Override 063 public Integer next() { 064 if(currBitIdx < bitSet.size()) { 065 int oldIdx = currBitIdx; 066 currBitIdx++; 067 findNextSetBit(); 068 return oldIdx; 069 } 070 071 return null; 072 } 073 074 /* 075 * (non-Javadoc) 076 * @see java.util.Iterator#remove() 077 */ 078 @Override 079 public void remove() { 080 bitSet.clear(currBitIdx); 081 findNextSetBit(); 082 } 083}