Java/Collections Data Structure/Iterator — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 07:25, 1 июня 2010
Содержание
- 1 An array iterator
- 2 An Iterator that returns the elements of a specified array, or other iterators etc.
- 3 An Iterator that wraps a number of Iterators
- 4 An Iterator to iterate over the elements of an array
- 5 An Iterator wrapper for an Enumeration.
- 6 An Iterator wrapper for an Object[], allow us to deal with all array like structures in a consistent manner.
- 7 Array Iterator
- 8 Create singleton Iterator
- 9 Cyclic Iteration
- 10 Demonstrate iterators.
- 11 De-mystify the Iterator interface, showing how to write a simple Iterator for an Array of Objects
- 12 Empty Iterator
- 13 EmptyIterator is an iterator which is empty.
- 14 Implements an java.util.Iterator over any array
- 15 Iterate a Collection and remove an item (Exception, wrong version)
- 16 Iterate over Set
- 17 Iterator class for sparse values in an array.
- 18 Iterator class for values contained in an array range.
- 19 Iterator Union of Iterators
- 20 Iterator Utils
- 21 Linked Iterator
- 22 Listing the Elements of a Collection
- 23 List Iterator
- 24 Prefetch Iterator
- 25 Protects an given iterator by preventing calls to remove().
- 26 Sorted Iterator
- 27 Treat an Iterator as an Iterable
- 28 Use an Iterator and remove the item with Iterator.remove()
- 29 Use the for-each for loop to cycle through a collection.
An array iterator
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
import java.io.Serializable;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* An array iterator.
*
* @version <tt>$Revision: 2800 $</tt>
* @author
*/
@SuppressWarnings("unchecked")
public class ArrayIterator implements Iterator, Serializable, Cloneable {
/** The serialVersionUID */
private static final long serialVersionUID = -6604583440222021075L;
/** Array to iterate over. */
protected final Object[] array;
/** The current position in the array. */
protected int index;
/**
* Construct an ArrayIterator.
*
* @param array
* The array to iterate over.
*/
public ArrayIterator(final Object[] array) {
this.array = array;
}
/**
* Returns true if there are more elements in the iteration.
*
* @return True if there are more elements in the iteration.
*/
public boolean hasNext() {
return index < array.length;
}
/**
* Returns the next element in the iteration.
*
* @return The next element in the iteration.
*
* @throws NoSuchElementException
* The are no more elements available.
*/
public Object next() {
if (!hasNext())
throw new NoSuchElementException();
return array[index++];
}
/**
* Unsupported.
*
* @throws UnsupportedOperationException
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Returns a shallow cloned copy of this object.
*
* @return A shallow cloned copy of this object.
*/
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
}
An Iterator that returns the elements of a specified array, or other iterators etc.
/* Copyright (c) 2001-2009, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* An Iterator that returns the elements of a specified array, or other
* iterators etc. The collection of objects returned depends on the
* constructor used.<p>
*
* Based on similar Enumerator code by boucherb@users
*
* @author fred@users
* @version 1.9.0
* @since HSQLDB 1.7.2
*/
public class WrapperIterator implements Iterator {
private static final Object[] emptyelements = new Object[0];
private Object[] elements;
private int i;
// chained iterators
private boolean chained;
private Iterator it1;
private Iterator it2;
/** return only not null elements */
private boolean notNull;
/**
* Constructor for an empty iterator. <p>
*/
public WrapperIterator() {
this.elements = emptyelements;
}
/**
* Constructor for all elements of the specified array. <p>
*
* @param elements the array of objects to enumerate
*/
public WrapperIterator(Object[] elements) {
this.elements = elements;
}
/**
* Constructor for not-null elements of specified array. <p>
*
* @param elements the array of objects to iterate
*/
public WrapperIterator(Object[] elements, boolean notNull) {
this.elements = elements;
this.notNull = notNull;
}
/**
* Constructor for a singleton object iterator
*
* @param element the single object to iterate
*/
public WrapperIterator(Object element) {
this.elements = new Object[]{ element };
}
/**
* Constructor for a chained iterator that returns the elements of the two
* specified iterators.
*/
public WrapperIterator(Iterator it1, Iterator it2) {
this.it1 = it1;
this.it2 = it2;
chained = true;
}
/**
* Tests if this iterator contains more elements. <p>
*
* @return <code>true</code> if this iterator contains more elements;
* <code>false</code> otherwise.
*/
public boolean hasNext() {
// for chained iterators
if (chained) {
if (it1 == null) {
if (it2 == null) {
return false;
}
if (it2.hasNext()) {
return true;
}
it2 = null;
return false;
} else {
if (it1.hasNext()) {
return true;
}
it1 = null;
return hasNext();
}
}
// for other interators
if (elements == null) {
return false;
}
for (; notNull && i < elements.length && elements[i] == null; i++) {}
if (i < elements.length) {
return true;
} else {
// release elements for garbage collection
elements = null;
return false;
}
}
/**
* Returns the next element.
*
* @return the next element
* @throws NoSuchElementException if there is no next element
*/
public Object next() {
// for chained iterators
if (chained) {
if (it1 == null) {
if (it2 == null) {
throw new NoSuchElementException();
}
if (it2.hasNext()) {
return it2.next();
}
it2 = null;
next();
} else {
if (it1.hasNext()) {
return it1.next();
}
it1 = null;
next();
}
}
// for other itertors
if (hasNext()) {
return elements[i++];
}
throw new NoSuchElementException();
}
public int nextInt() {
throw new NoSuchElementException();
}
public long nextLong() {
throw new NoSuchElementException();
}
public void remove() {
throw new NoSuchElementException();
}
public void setValue(Object value) {
throw new NoSuchElementException();
}
}
An Iterator that wraps a number of Iterators
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
import java.util.Iterator;
import java.util.List;
/**
* An JoinedIterator is an Iterator that wraps a number of Iterators.
*
* This class makes multiple iterators look like one to the caller.
* When any method from the Iterator interface is called, the JoinedIterator
* will delegate to a single underlying Iterator. The JoinedIterator will
* invoke the Iterators in sequence until all Iterators are exhausted.
*
*/
public class JoinedIterator implements Iterator {
private static final Iterator[] ITERATORS = {};
// wrapped iterators
private Iterator[] iterators;
// index of current iterator in the wrapped iterators array
private int currentIteratorIndex;
// the current iterator
private Iterator currentIterator;
// the last used iterator
private Iterator lastUsedIterator;
public JoinedIterator(List iterators) {
this( (Iterator[]) iterators.toArray(ITERATORS) );
}
public JoinedIterator(Iterator[] iterators) {
if( iterators==null )
throw new NullPointerException("Unexpected NULL iterators argument");
this.iterators = iterators;
}
public JoinedIterator(Iterator first, Iterator second) {
this( new Iterator[] { first, second } );
}
public boolean hasNext() {
updateCurrentIterator();
return currentIterator.hasNext();
}
public Object next() {
updateCurrentIterator();
return currentIterator.next();
}
public void remove() {
updateCurrentIterator();
lastUsedIterator.remove();
}
// call this before any Iterator method to make sure that the current Iterator
// is not exhausted
protected void updateCurrentIterator() {
if (currentIterator == null) {
if( iterators.length==0 ) {
currentIterator = EmptyIterator.emptyIterator;
}
else {
currentIterator = iterators[0];
}
// set last used iterator here, in case the user calls remove
// before calling hasNext() or next() (although they shouldn"t)
lastUsedIterator = currentIterator;
}
while (! currentIterator.hasNext() && currentIteratorIndex < iterators.length - 1) {
currentIteratorIndex++;
currentIterator = iterators[currentIteratorIndex];
}
}
}
/* Copyright 2004 BEA Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class EmptyIterator implements java.util.Iterator {
public static final EmptyIterator emptyIterator = new EmptyIterator();
public boolean hasNext() { return false; }
public Object next() { return null; }
public void remove() {
throw new UnsupportedOperationException();
}
}
An Iterator to iterate over the elements of an array
/*
* This file is part of the Echo Web Application Framework (hereinafter "Echo").
* Copyright (C) 2002-2009 NextApp, Inc.
*
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*/
import java.util.Iterator;
/**
* An <code>Iterator</code> to iterate over the elements of an array.
*/
public class ArrayIterator
implements Iterator {
/** Current index. */
private int index = 0;
/** The iterated array. */
private Object[] array;
/**
* Creates a new <code>ArrayIterator</code>.
*
* @param array the array
*/
public ArrayIterator(Object[] array) {
super();
this.array = array;
}
/**
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return index < array.length;
}
/**
* @see java.util.Iterator#next()
*/
public Object next() {
return array[index++];
}
/**
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
An Iterator wrapper for an Enumeration.
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.Enumeration;
import java.util.Iterator;
/**
* An Iterator wrapper for an Enumeration.
*
* @author
* @version $Id: EnumerationIterator.java 463298 2006-10-12 16:10:32Z henning $
*/
public class EnumerationIterator implements Iterator {
/**
* The enumeration to iterate.
*/
private Enumeration enumeration = null;
/**
* Creates a new iteratorwrapper instance for the specified Enumeration.
*
* @param enumeration
* The Enumeration to wrap.
*/
public EnumerationIterator(Enumeration enumeration) {
this.enumeration = enumeration;
}
/**
* Move to next element in the array.
*
* @return The next object in the array.
*/
public Object next() {
return enumeration.nextElement();
}
/**
* Check to see if there is another element in the array.
*
* @return Whether there is another element.
*/
public boolean hasNext() {
return enumeration.hasMoreElements();
}
/**
* Unimplemented. No analogy in Enumeration
*/
public void remove() {
// not implemented
}
}
An Iterator wrapper for an Object[], allow us to deal with all array like structures in a consistent manner.
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.lang.reflect.Array;
/**
* <p>
* An Iterator wrapper for an Object[]. This will
* allow us to deal with all array like structures
* in a consistent manner.
* </p>
* <p>
* WARNING : this class"s operations are NOT synchronized.
* It is meant to be used in a single thread, newly created
* for each use in the #foreach() directive.
* If this is used or shared, synchronize in the
* next() method.
* </p>
*
* @author
* @version $Id: ArrayIterator.java 463298 2006-10-12 16:10:32Z henning $
*/
public class ArrayIterator implements Iterator
{
/**
* The objects to iterate.
*/
private Object array;
/**
* The current position and size in the array.
*/
private int pos;
private int size;
/**
* Creates a new iterator instance for the specified array.
*
* @param array The array for which an iterator is desired.
*/
public ArrayIterator(Object array)
{
/*
* if this isn"t an array, then throw. Note that this is
* for internal use - so this should never happen - if it does
* we screwed up.
*/
if ( !array.getClass().isArray() )
{
throw new IllegalArgumentException(
"Programmer error : internal ArrayIterator invoked w/o array");
}
this.array = array;
pos = 0;
size = Array.getLength( this.array );
}
/**
* Move to next element in the array.
*
* @return The next object in the array.
*/
public Object next()
{
if (pos < size )
return Array.get( array, pos++);
/*
* we screwed up...
*/
throw new NoSuchElementException("No more elements: " + pos +
" / " + size);
}
/**
* Check to see if there is another element in the array.
*
* @return Whether there is another element.
*/
public boolean hasNext()
{
return (pos < size );
}
/**
* No op--merely added to satify the <code>Iterator</code> interface.
*/
public void remove()
{
throw new UnsupportedOperationException();
}
}
Array Iterator
/**
GNU LESSER GENERAL PUBLIC LICENSE
Copyright (C) 2006 The Lobo Project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: lobochief@users.sourceforge.net
*/
/*
* Created on Apr 17, 2005
*/
import java.util.*;
/**
* @author J. H. S.
*/
public class ArrayUtilities {
/**
*
*/
private ArrayUtilities() {
super();
}
public static Iterator iterator(Object[] array, int offset, int length) {
return new ArrayIterator(array, offset, length);
}
private static class ArrayIterator implements Iterator {
private final Object[] array;
private final int top;
private int offset;
public ArrayIterator(Object[] array, int offset, int length) {
this.array = array;
this.offset = offset;
this.top = offset + length;
}
/* (non-Javadoc)
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return this.offset < this.top;
}
/* (non-Javadoc)
* @see java.util.Iterator#next()
*/
public Object next() {
return this.array[this.offset++];
}
/* (non-Javadoc)
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
}
Create singleton Iterator
/*
GNU LESSER GENERAL PUBLIC LICENSE
Copyright (C) 2006 The Lobo Project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: lobochief@users.sourceforge.net
*/
/*
* Created on Jun 9, 2005
*/
import java.util.*;
/**
* @author J. H. S.
*/
class CollectionUtilities {
/**
*
*/
private CollectionUtilities() {
super();
}
public static Enumeration getIteratorEnumeration(final Iterator i) {
return new Enumeration() {
public boolean hasMoreElements() {
return i.hasNext();
}
public Object nextElement() {
return i.next();
}
};
}
public static Iterator iteratorUnion(final Iterator[] iterators) {
return new Iterator() {
private int iteratorIndex = 0;
private Iterator current = iterators.length > 0 ? iterators[0] : null;
public boolean hasNext() {
for(;;) {
if(current == null) {
return false;
}
if(current.hasNext()) {
return true;
}
iteratorIndex++;
current = iteratorIndex >= iterators.length ? null : iterators[iteratorIndex];
}
}
public Object next() {
for(;;) {
if(this.current == null) {
throw new NoSuchElementException();
}
try {
return this.current.next();
} catch(NoSuchElementException nse) {
this.iteratorIndex++;
this.current = this.iteratorIndex >= iterators.length ? null : iterators[this.iteratorIndex];
}
}
}
public void remove() {
if(this.current == null) {
throw new NoSuchElementException();
}
this.current.remove();
}
};
}
public static Collection reverse(Collection collection) {
LinkedList newCollection = new LinkedList();
Iterator i = collection.iterator();
while(i.hasNext()) {
newCollection.addFirst(i.next());
}
return newCollection;
}
public static Iterator singletonIterator(final Object item) {
return new Iterator() {
private boolean gotItem = false;
public boolean hasNext() {
return !this.gotItem;
}
public Object next() {
if(this.gotItem) {
throw new NoSuchElementException();
}
this.gotItem = true;
return item;
}
public void remove() {
if(!this.gotItem) {
this.gotItem = true;
}
else {
throw new NoSuchElementException();
}
}
};
}
}
Cyclic Iteration
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.SortedMap;
/** Provide an cyclic {@link Iterator} for a {@link SortedMap}.
* The {@link Iterator} navigates the entries of the map
* according to the map"s ordering.
* If the {@link Iterator} hits the last entry of the map,
* it will then continue from the first entry.
*/
public class CyclicIteration<K, V> implements Iterable<Map.Entry<K, V>> {
private final SortedMap<K, V> navigablemap;
private final SortedMap<K, V> tailmap;
private final K startingkey;
/** Construct an {@link Iterable} object,
* so that an {@link Iterator} can be created
* for iterating the given {@link SortedMap}.
* The iteration begins from the starting key exclusively.
*/
public CyclicIteration(SortedMap<K, V> navigablemap, K startingkey) {
this.startingkey = startingkey;
if (navigablemap == null || navigablemap.isEmpty()) {
this.navigablemap = null;
this.tailmap = null;
}
else {
this.navigablemap = navigablemap;
this.tailmap = navigablemap.tailMap(startingkey);
}
}
/** {@inheritDoc} */
public Iterator<Map.Entry<K, V>> iterator() {
return new CyclicIterator();
}
/** An {@link Iterator} for {@link CyclicIteration}. */
private class CyclicIterator implements Iterator<Map.Entry<K, V>> {
private boolean hasnext;
private Iterator<Map.Entry<K, V>> i;
/** The first entry to begin. */
private final Map.Entry<K, V> first;
/** The next entry. */
private Map.Entry<K, V> next;
private CyclicIterator() {
hasnext = navigablemap != null;
if (hasnext) {
i = tailmap.entrySet().iterator();
Map.Entry<K, V> e = nextEntry();
if (e.getKey().equals(startingkey)) {
e = nextEntry();
}
first = e;
next = first;
}
else {
i = null;
first = null;
next = null;
}
}
private Map.Entry<K, V> nextEntry() {
if (!i.hasNext()) {
i = navigablemap.entrySet().iterator();
}
return i.next();
}
/** {@inheritDoc} */
public boolean hasNext() {
return hasnext;
}
/** {@inheritDoc} */
public Map.Entry<K, V> next() {
if (!hasnext) {
throw new NoSuchElementException();
}
final Map.Entry<K, V> curr = next;
next = nextEntry();
hasnext = !next.equals(first);
return curr;
}
/** Not supported */
public void remove() {
throw new UnsupportedOperationException("Not supported");
}
}
}
Demonstrate iterators.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
class IteratorDemo {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
Iterator<String> itr = al.iterator();
while (itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
ListIterator<String> litr = al.listIterator();
while (litr.hasNext()) {
String element = litr.next();
litr.set(element + "+");
}
itr = al.iterator();
while (itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
while (litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element + " ");
}
}
}
De-mystify the Iterator interface, showing how to write a simple Iterator for an Array of Objects
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.util.Iterator;
/**
* De-mystify the Iterator interface, showing how to write a simple Iterator for
* an Array of Objects.
*
* @author Ian Darwin, http://www.darwinsys.ru/
* @version $Id: ArrayIterator.java,v 1.10 2004/06/16 17:39:33 ian Exp $
*/
public class ArrayIterator implements Iterator {
/** The data to be iterated over. */
protected Object[] data;
protected int index = 0;
/**
* Construct an ArrayIterator object.
*
* @param d
* The array of objects to be iterated over.
*/
public ArrayIterator(final Object[] d) {
setData(d);
}
/**
* (Re)set the data array to the given array, and reset the iterator.
*
* @param d
* The array of objects to be iterated over.
*/
public void setData(final Object[] d) {
this.data = d;
index = 0;
}
/**
* Tell if there are any more elements.
*
* @return true if not at the end, i.e., if next() will succeed.
* @return false if next() will throw an exception.
*/
public boolean hasNext() {
return (index < data.length);
}
/** Returns the next element from the data */
public Object next() {
if (hasNext()) {
return data[index++];
}
throw new IndexOutOfBoundsException("only " + data.length + " elements");
}
/**
* Remove the object that next() just returned. An Iterator is not required
* to support this interface, and we certainly don"t!
*/
public void remove() {
throw new UnsupportedOperationException(
"This demo does not implement the remove method");
}
}
Empty Iterator
/*
* Copyright Javelin Software, All rights reserved.
*/
import java.util.*;
/**
* An EmptyIterator.
*
* @author Robin Sharp
*/
public class EmptyIterator implements Iterator
{
public static Iterator getInstance()
{
return iterator;
}
/**
* @return false;
*/
public boolean hasNext()
{
return false;
}
/**
* @return null
*/
public Object next()
{
throw new NoSuchElementException();
}
/**
* No-op
*/
public void remove()
{
throw new UnsupportedOperationException();
}
protected static Iterator iterator = new EmptyIterator();
}
EmptyIterator is an iterator which is empty.
/**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/util/branches/sakai_2-5-4/util-util/util/src/java/org/sakaiproject/util/EmptyIterator.java $
* $Id: EmptyIterator.java 6832 2006-03-21 20:43:34Z ggolden@umich.edu $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
// imports
import java.util.Iterator;
/**
* <p>
* EmptyIterator is an iterator which is empty.
* </p>
*/
public class EmptyIterator implements Iterator
{
public Object next()
{
return null;
}
public boolean hasNext()
{
return false;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
Implements an java.util.Iterator over any array
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.lang.reflect.Array;
import java.util.NoSuchElementException;
/**
* Implements an {@link java.util.Iterator Iterator} over any array.
* <p>
* The array can be either an array of object or of primitives. If you know
* that you have an object array, the
* {@link org.apache.rumons.collections.iterators.ObjectArrayIterator ObjectArrayIterator}
* class is a better choice, as it will perform better.
* <p>
* The iterator implements a {@link #reset} method, allowing the reset of
* the iterator back to the start if required.
*
* @since Commons Collections 1.0
* @version $Revision$ $Date$
*
* @author James Strachan
* @author Mauricio S. Moura
* @author Michael A. Smith
* @author Neil O"Toole
* @author Stephen Colebourne
*/
public class ArrayIterator implements java.util.Iterator {
/** The array to iterate over */
protected Object array;
/** The end index to loop to */
protected int endIndex = 0;
/** The current iterator index */
protected int index = 0;
/**
* Constructs an ArrayIterator that will iterate over the values in the
* specified array.
*
* @param array the array to iterate over.
* @throws IllegalArgumentException if <code>array</code> is not an array.
* @throws NullPointerException if <code>array</code> is <code>null</code>
*/
public ArrayIterator(final Object array) {
setArray(array);
}
/**
* Checks whether the index is valid or not.
*
* @param bound the index to check
* @param type the index type (for error messages)
* @throws IndexOutOfBoundsException if the index is invalid
*/
protected void checkBound(final int bound, final String type ) {
if (bound > this.endIndex) {
throw new ArrayIndexOutOfBoundsException(
"Attempt to make an ArrayIterator that " + type +
"s beyond the end of the array. "
);
}
if (bound < 0) {
throw new ArrayIndexOutOfBoundsException(
"Attempt to make an ArrayIterator that " + type +
"s before the start of the array. "
);
}
}
// Iterator interface
//-----------------------------------------------------------------------
/**
* Returns true if there are more elements to return from the array.
*
* @return true if there is a next element to return
*/
public boolean hasNext() {
return (index < endIndex);
}
/**
* Returns the next element in the array.
*
* @return the next element in the array
* @throws NoSuchElementException if all the elements in the array
* have already been returned
*/
public Object next() {
if (hasNext() == false) {
throw new NoSuchElementException();
}
return Array.get(array, index++);
}
/**
* Throws {@link UnsupportedOperationException}.
*
* @throws UnsupportedOperationException always
*/
public void remove() {
throw new UnsupportedOperationException("remove() method is not supported");
}
// Properties
//-----------------------------------------------------------------------
/**
* Gets the array that this iterator is iterating over.
*
* @return the array this iterator iterates over, or <code>null</code> if
* the no-arg constructor was used and {@link #setArray(Object)} has never
* been called with a valid array.
*/
public Object getArray() {
return array;
}
/**
* Sets the array that the ArrayIterator should iterate over.
* <p>
* If an array has previously been set (using the single-arg constructor
* or this method) then that array is discarded in favour of this one.
* Iteration is restarted at the start of the new array.
* Although this can be used to reset iteration, the {@link #clear()} method
* is a more effective choice.
*
* @param array the array that the iterator should iterate over.
* @throws IllegalArgumentException if <code>array</code> is not an array.
* @throws NullPointerException if <code>array</code> is <code>null</code>
*/
private void setArray(final Object array) {
// Array.getLength throws IllegalArgumentException if the object is not
// an array or NullPointerException if the object is null. This call
// is made before saving the array and resetting the index so that the
// array iterator remains in a consistent state if the argument is not
// an array or is null.
this.endIndex = Array.getLength(array);
this.array = array;
this.index = 0;
}
}
Iterate a Collection and remove an item (Exception, wrong version)
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String args[]) {
List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("C");
list.add("C");
list.add("C");
list.add("C");
for (String s : list) {
if (s.equals("B")) {
list.remove("B");
}
System.out.println(s);
}
}
}
/*A
B
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Main.main(Main.java:17)
*/
Iterate over Set
import java.util.*;
public class Iterate {
public static void main (String args[]) {
String elements[] = {"Irish Setter", "Poodle",
"English Setter", "Gordon Setter", "Pug"};
Set set = new HashSet(Arrays.asList(elements));
Iterator iter = set.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
}
Iterator class for sparse values in an array.
/*
* Copyright (c) 2000-2007, Dennis M. Sosnoski. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided
* with the distribution. Neither the name of JiBX nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Iterator class for sparse values in an array. This type of iterator
* can be used for an object array which has references interspersed with
* <code>null</code>s.
*
* @author Dennis M. Sosnoski
*/
public class SparseArrayIterator implements Iterator
{
/** Empty iterator. */
public static final SparseArrayIterator EMPTY_ITERATOR =
new SparseArrayIterator(new Object[0]);
/** Array supplying values for iteration. */
private Object[] m_array;
/** Offset of next iteration value. */
private int m_offset;
/**
* Internal constructor.
*
* @param array array containing values to be iterated
*/
private SparseArrayIterator(Object[] array) {
m_array = array;
m_offset = -1;
advance();
}
/**
* Advance to next iteration value. This advances the current position in
* the array to the next non-<code>null</code> value.
*
* @return <code>true</code> if element available, <code>false</code> if
* not
*/
protected boolean advance() {
while (++m_offset < m_array.length) {
if (m_array[m_offset] != null) {
return true;
}
}
return false;
}
/**
* Check for iteration element available.
*
* @return <code>true</code> if element available, <code>false</code> if
* not
*/
public boolean hasNext() {
return m_offset < m_array.length;
}
/**
* Get next iteration element.
*
* @return next iteration element
* @exception NoSuchElementException if past end of iteration
*/
public Object next() {
if (m_offset < m_array.length) {
Object result = m_array[m_offset];
advance();
return result;
} else {
throw new NoSuchElementException();
}
}
/**
* Remove element from iteration. This optional operation is not supported
* and always throws an exception.
*
* @exception UnsupportedOperationException for unsupported operation
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Build iterator.
*
* @param array array containing values to be iterated (may be
* <code>null</code>)
* @return constructed iterator
*/
public static Iterator buildIterator(Object[] array) {
if (array == null || array.length == 0) {
return EMPTY_ITERATOR;
} else {
return new SparseArrayIterator(array);
}
}
}
Iterator class for values contained in an array range.
/*
Copyright (c) 2000-2005, Dennis M. Sosnoski.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of JiBX nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Iterator class for values contained in an array range. This type of iterator
* can be used for any contiguous range of items in an object array.
*
* @author Dennis M. Sosnoski
* @version 1.1
*/
public class ArrayRangeIterator implements Iterator
{
/** Empty iterator used whenever possible. */
public static final ArrayRangeIterator EMPTY_ITERATOR =
new ArrayRangeIterator(null, 0, 0);
/** Array supplying values for iteration. */
protected Object[] m_array;
/** Offset of next iteration value. */
protected int m_offset;
/** Ending offset for values. */
protected int m_limit;
/**
* Internal constructor.
*
* @param array array containing values to be iterated
* @param start starting offset in array
* @param limit offset past end of values
*/
private ArrayRangeIterator(Object[] array, int start, int limit) {
m_array = array;
m_offset = start;
m_limit = limit;
}
/**
* Check for iteration element available.
*
* @return <code>true</code> if element available, <code>false</code> if
* not
*/
public boolean hasNext() {
return m_offset < m_limit;
}
/**
* Get next iteration element.
*
* @return next iteration element
* @exception NoSuchElementException if past end of iteration
*/
public Object next() {
if (m_offset < m_limit) {
return m_array[m_offset++];
} else {
throw new NoSuchElementException();
}
}
/**
* Remove element from iteration. This optional operation is not supported
* and always throws an exception.
*
* @exception UnsupportedOperationException for unsupported operation
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Build iterator.
*
* @param array array containing values to be iterated (may be
* <code>null</code>)
* @param start starting offset in array
* @param limit offset past end of values
* @return constructed iterator
*/
public static Iterator buildIterator(Object[] array, int start, int limit) {
if (array == null || start >= limit) {
return EMPTY_ITERATOR;
} else {
return new ArrayRangeIterator(array, start, limit);
}
}
}
Iterator Union of Iterators
/*
GNU LESSER GENERAL PUBLIC LICENSE
Copyright (C) 2006 The Lobo Project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: lobochief@users.sourceforge.net
*/
/*
* Created on Jun 9, 2005
*/
import java.util.*;
/**
* @author J. H. S.
*/
class CollectionUtilities {
/**
*
*/
private CollectionUtilities() {
super();
}
public static Enumeration getIteratorEnumeration(final Iterator i) {
return new Enumeration() {
public boolean hasMoreElements() {
return i.hasNext();
}
public Object nextElement() {
return i.next();
}
};
}
public static Iterator iteratorUnion(final Iterator[] iterators) {
return new Iterator() {
private int iteratorIndex = 0;
private Iterator current = iterators.length > 0 ? iterators[0] : null;
public boolean hasNext() {
for(;;) {
if(current == null) {
return false;
}
if(current.hasNext()) {
return true;
}
iteratorIndex++;
current = iteratorIndex >= iterators.length ? null : iterators[iteratorIndex];
}
}
public Object next() {
for(;;) {
if(this.current == null) {
throw new NoSuchElementException();
}
try {
return this.current.next();
} catch(NoSuchElementException nse) {
this.iteratorIndex++;
this.current = this.iteratorIndex >= iterators.length ? null : iterators[this.iteratorIndex];
}
}
}
public void remove() {
if(this.current == null) {
throw new NoSuchElementException();
}
this.current.remove();
}
};
}
public static Collection reverse(Collection collection) {
LinkedList newCollection = new LinkedList();
Iterator i = collection.iterator();
while(i.hasNext()) {
newCollection.addFirst(i.next());
}
return newCollection;
}
public static Iterator singletonIterator(final Object item) {
return new Iterator() {
private boolean gotItem = false;
public boolean hasNext() {
return !this.gotItem;
}
public Object next() {
if(this.gotItem) {
throw new NoSuchElementException();
}
this.gotItem = true;
return item;
}
public void remove() {
if(!this.gotItem) {
this.gotItem = true;
}
else {
throw new NoSuchElementException();
}
}
};
}
}
Iterator Utils
/*
* Distributed as part of debuggen v.0.1.0
*
* Copyright (C) 2005 Machinery For Change, Inc.
*
* Author: Steve Waldman <swaldman@mchange.ru>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 2.1, as
* published by the Free Software Foundation.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software; see the file LICENSE. If not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
import java.util.*;
import java.lang.reflect.Array;
public final class IteratorUtils
{
public final static Iterator EMPTY_ITERATOR = new Iterator()
{
public boolean hasNext()
{ return false; }
public Object next()
{ throw new NoSuchElementException(); }
public void remove()
{ throw new IllegalStateException(); }
};
public static Iterator oneElementUnmodifiableIterator(final Object elem)
{
return new Iterator()
{
boolean shot = false;
public boolean hasNext() { return (!shot); }
public Object next()
{
if (shot)
throw new NoSuchElementException();
else
{
shot = true;
return elem;
}
}
public void remove()
{ throw new UnsupportedOperationException("remove() not supported."); }
};
}
public static boolean equivalent(Iterator ii, Iterator jj)
{
while (true)
{
boolean ii_hasnext = ii.hasNext();
boolean jj_hasnext = jj.hasNext();
if (ii_hasnext ^ jj_hasnext)
return false;
else if (ii_hasnext)
{
Object iiNext = ii.next();
Object jjNext = jj.next();
if (iiNext == jjNext)
continue;
else if (iiNext == null)
return false;
else if (!iiNext.equals(jjNext))
return false;
}
else return true;
}
}
public static ArrayList toArrayList(Iterator ii, int initial_capacity)
{
ArrayList out = new ArrayList(initial_capacity);
while (ii.hasNext())
out.add(ii.next());
return out;
}
/**
* Fills an array with the contents of an iterator. If the array is too small,
* it will contain the first portion of the iterator. If the array can contain
* more elements than the iterator, extra elements are left untouched, unless
* null_terminate is set to true, in which case the element immediately following
* the last from the iterator is set to null. (This method is intended to make
* it easy to implement Collection.toArray(Object[] oo) methods...
*
* @param null_terminate iff there is extra space in the array, set the element
* immediately after the last from the iterator to null.
*/
public static void fillArray(Iterator ii, Object[] fillMe, boolean null_terminate)
{
int i = 0;
int len = fillMe.length;
while ( i < len && ii.hasNext() )
fillMe[ i++ ] = ii.next();
if (null_terminate && i < len)
fillMe[i] = null;
}
public static void fillArray(Iterator ii, Object[] fillMe)
{ fillArray( ii, fillMe, false); }
/**
* @param null_terminate iff there is extra space in the array, set the element
* immediately after the last from the iterator to null.
*/
public static Object[] toArray(Iterator ii, int array_size, Class componentClass, boolean null_terminate)
{
Object[] out = (Object[]) Array.newInstance( componentClass, array_size );
fillArray(ii, out, null_terminate);
return out;
}
public static Object[] toArray(Iterator ii, int array_size, Class componentClass)
{ return toArray( ii, array_size, componentClass, false ); }
/**
* Designed to help implement Collection.toArray(Object[] )methods... does
* the right thing if you can express an iterator and know the size of your
* Collection.
*/
public static Object[] toArray(Iterator ii, int ii_size, Object[] maybeFillMe)
{
if (maybeFillMe.length >= ii_size)
{
fillArray( ii, maybeFillMe, true );
return maybeFillMe;
}
else
{
Class componentType = maybeFillMe.getClass().getComponentType();
return toArray( ii, ii_size, componentType );
}
}
private IteratorUtils()
{}
}
Linked Iterator
/*
* $Header: /cvsroot/jaxen/jaxen/src/java/main/org/jaxen/util/LinkedIterator.java,v 1.2 2002/04/26 17:17:36 jstrachan Exp $
* $Revision: 1.2 $
* $Date: 2002/04/26 17:17:36 $
*
*
*
* Copyright (C) 2000-2002 bob mcwhirter & James Strachan.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions, and the disclaimer that follows
* these conditions in the documentation and/or other materials
* provided with the distribution.
*
* 3. The name "Jaxen" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact license@jaxen.org.
*
* 4. Products derived from this software may not be called "Jaxen", nor
* may "Jaxen" appear in their name, without prior written permission
* from the Jaxen Project Management (pm@jaxen.org).
*
* In addition, we request (but do not require) that you include in the
* end-user documentation provided with the redistribution and/or in the
* software itself an acknowledgement equivalent to the following:
* "This product includes software developed by the
* Jaxen Project (http://www.jaxen.org/)."
* Alternatively, the acknowledgment may be graphical using the logos
* available at http://www.jaxen.org/
*
* THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE Jaxen AUTHORS OR THE PROJECT
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Jaxen Project and was originally
* created by bob mcwhirter <bob@werken.ru> and
* James Strachan <jstrachan@apache.org>. For more information on the
* Jaxen Project, please see <http://www.jaxen.org/>.
*
* $Id: LinkedIterator.java,v 1.2 2002/04/26 17:17:36 jstrachan Exp $
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.List;
import java.util.ArrayList;
public class LinkedIterator implements Iterator
{
private List iterators;
private int cur;
public LinkedIterator()
{
this.iterators = new ArrayList();
this.cur = 0;
}
public void addIterator(Iterator i)
{
this.iterators.add( i );
}
public boolean hasNext()
{
boolean has = false;
if ( this.cur < this.iterators.size() )
{
has = ((Iterator)this.iterators.get( this.cur )).hasNext();
if ( ! has
&&
this.cur < this.iterators.size() )
{
++this.cur;
has = hasNext();
}
}
else
{
has = false;
}
return has;
}
public Object next()
{
if ( ! hasNext() )
{
throw new NoSuchElementException();
}
return ((Iterator)this.iterators.get( this.cur )).next();
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
Listing the Elements of a Collection
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] argv) {
List collection = new ArrayList();
// For a set or list
for (Iterator it = collection.iterator(); it.hasNext();) {
Object element = it.next();
}
Map map = new HashMap();
// For keys of a map
for (Iterator it = map.keySet().iterator(); it.hasNext();) {
Object key = it.next();
}
// For values of a map
for (Iterator it = map.values().iterator(); it.hasNext();) {
Object value = it.next();
}
// For both the keys and values of a map
for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
}
}
}
List Iterator
import java.io.IOException;
public class ListIterator {
private Link current;
private Link previous;
private LinkList ourList;
public ListIterator(LinkList list) {
ourList = list;
reset();
}
// start at "first"
public void reset() {
current = ourList.getFirst();
previous = null;
}
public boolean atEnd() {
return (current.next == null);
}
// go to next link
public void nextLink() {
previous = current;
current = current.next;
}
public Link getCurrent() {
return current;
}
public void insertAfter(long dd) {
Link newLink = new Link(dd);
if (ourList.isEmpty()) {
ourList.setFirst(newLink);
current = newLink;
} else // not empty
{
newLink.next = current.next;
current.next = newLink;
nextLink(); // point to new link
}
}
public void insertBefore(long data) {
Link newLink = new Link(data);
if (previous == null) {
newLink.next = ourList.getFirst();
ourList.setFirst(newLink);
reset();
}// not beginning
else {
newLink.next = previous.next;
previous.next = newLink;
current = newLink;
}
}
// delete item at current
public long deleteCurrent() {
long value = current.dData;
// beginning of list
if (previous == null) {
ourList.setFirst(current.next);
reset();
}// not beginning
else {
previous.next = current.next;
if (atEnd())
reset();
else
current = current.next;
}
return value;
}
public static void main(String[] args) throws IOException {
LinkList theList = new LinkList();
ListIterator iter1 = theList.getIterator();
long value;
iter1.insertAfter(20);
iter1.insertAfter(40);
iter1.insertAfter(80);
iter1.insertBefore(60);
if (!theList.isEmpty())
theList.displayList();
else
System.out.println("List is empty");
}
}
class LinkList {
private Link first;
public LinkList() {
first = null;
}
public Link getFirst() {
return first;
}
public void setFirst(Link f) {
first = f;
}
public boolean isEmpty() {
return first == null;
}
public ListIterator getIterator() {
return new ListIterator(this);
}
public void displayList() {
Link current = first;
while (current != null) {
current.displayLink();
current = current.next;
}
System.out.println("");
}
}
class Link {
public long dData;
public Link next;
public Link(long dd) {
dData = dd;
}
public void displayLink() {
System.out.print(dData + " ");
}
}
Prefetch Iterator
/*
* JGraphT : a free Java graph-theory library
*
*
* Project Info: http://jgrapht.sourceforge.net/
* Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh)
*
* (C) Copyright 2003-2007, by Barak Naveh and Contributors.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
/* -----------------
* PrefetchIterator.java
* -----------------
* (C) Copyright 2005-2007, by Assaf Lehr and Contributors.
*
* Original Author: Assaf Lehr
* Contributor(s): -
*
* $Id: PrefetchIterator.java 568 2007-09-30 00:12:18Z perfecthash $
*
* Changes
* -------
*/
import java.util.*;
/**
* Utility class to help implement an iterator/enumerator in which the hasNext()
* method needs to calculate the next elements ahead of time.
*
* <p>Many classes which implement an iterator face a common problem: if there
* is no easy way to calculate hasNext() other than to call getNext(), then they
* save the result for fetching in the next call to getNext(). This utility
* helps in doing just that.
*
* <p><b>Usage:</b> The new iterator class will hold this class as a member
* variable and forward the hasNext() and next() to it. When creating an
* instance of this class, you supply it with a functor that is doing the real
* job of calculating the next element.
*
* <pre><code>
//This class supllies enumeration of integer till 100.
public class IteratorExample implements Enumeration{
private int counter=0;
private PrefetchIterator nextSupplier;
IteratorExample()
{
nextSupplier = new PrefetchIterator(new PrefetchIterator.NextElementFunctor(){
public Object nextElement() throws NoSuchElementException {
counter++;
if (counter>=100)
throw new NoSuchElementException();
else
return new Integer(counter);
}
});
}
//forwarding to nextSupplier and return its returned value
public boolean hasMoreElements() {
return this.nextSupplier.hasMoreElements();
}
// forwarding to nextSupplier and return its returned value
public Object nextElement() {
return this.nextSupplier.nextElement();
}
}</pre>
* </code>
*
* @author Assaf_Lehr
*/
public class PrefetchIterator<E>
implements Iterator<E>,
Enumeration<E>
{
//~ Instance fields --------------------------------------------------------
private NextElementFunctor<E> innerEnum;
private E getNextLastResult;
private boolean isGetNextLastResultUpToDate = false;
private boolean endOfEnumerationReached = false;
private boolean flagIsEnumerationStartedEmpty = true;
private int innerFunctorUsageCounter = 0;
//~ Constructors -----------------------------------------------------------
public PrefetchIterator(NextElementFunctor<E> aEnum)
{
innerEnum = aEnum;
}
//~ Methods ----------------------------------------------------------------
/**
* Serves as one contact place to the functor; all must use it and not
* directly the NextElementFunctor.
*/
private E getNextElementFromInnerFunctor()
{
innerFunctorUsageCounter++;
E result = this.innerEnum.nextElement();
// if we got here , an exception was not thrown, so at least
// one time a good value returned
flagIsEnumerationStartedEmpty = false;
return result;
}
/**
* 1. Retrieves the saved value or calculates it if it does not exist 2.
* Changes isGetNextLastResultUpToDate to false. (Because it does not save
* the NEXT element now; it saves the current one!)
*/
public E nextElement()
{
E result = null;
if (this.isGetNextLastResultUpToDate) {
result = this.getNextLastResult;
} else {
result = getNextElementFromInnerFunctor();
}
this.isGetNextLastResultUpToDate = false;
return result;
}
/**
* If (isGetNextLastResultUpToDate==true) returns true else 1. calculates
* getNext() and saves it 2. sets isGetNextLastResultUpToDate to true.
*/
public boolean hasMoreElements()
{
if (endOfEnumerationReached) {
return false;
}
if (isGetNextLastResultUpToDate) {
return true;
} else {
try {
this.getNextLastResult = getNextElementFromInnerFunctor();
this.isGetNextLastResultUpToDate = true;
return true;
} catch (NoSuchElementException noSuchE) {
endOfEnumerationReached = true;
return false;
}
} // else
} // method
/**
* Tests whether the enumeration started as an empty one. It does not matter
* if it hasMoreElements() now, only at initialization time. Efficiency: if
* nextElements(), hasMoreElements() were never used, it activates the
* hasMoreElements() once. Else it is immediately(O(1))
*/
public boolean isEnumerationStartedEmpty()
{
if (this.innerFunctorUsageCounter == 0) {
if (hasMoreElements()) {
return false;
} else {
return true;
}
} else // it is not the first time , so use the saved value
// which was initilaizeed during a call to
// getNextElementFromInnerFunctor
{
return flagIsEnumerationStartedEmpty;
}
}
public boolean hasNext()
{
return this.hasMoreElements();
}
public E next()
{
return this.nextElement();
}
/**
* Always throws UnsupportedOperationException.
*/
public void remove()
throws UnsupportedOperationException
{
throw new UnsupportedOperationException();
}
//~ Inner Interfaces -------------------------------------------------------
public interface NextElementFunctor<EE>
{
/**
* You must implement that NoSuchElementException is thrown on
* nextElement() if it is out of bound.
*/
public EE nextElement()
throws NoSuchElementException;
}
}
// End PrefetchIterator.java
/////////////////////////
/*
* JGraphT : a free Java graph-theory library
*
*
* Project Info: http://jgrapht.sourceforge.net/
* Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh)
*
* (C) Copyright 2003-2007, by Barak Naveh and Contributors.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
/* -----------------
* PrefetchIteratorTest.java
* -----------------
* (C) Copyright 2005-2007, by Assaf Lehr and Contributors.
*
* Original Author: Assaf Lehr
* Contributor(s): -
*
* $Id: PrefetchIteratorTest.java 568 2007-09-30 00:12:18Z perfecthash $
*
* Changes
* -------
*/
package org.jgrapht.util;
import java.util.*;
import junit.framework.*;
public class PrefetchIteratorTest
extends TestCase
{
//~ Methods ----------------------------------------------------------------
public void testIteratorInterface()
{
Iterator iterator = new IterateFrom1To99();
for (int i = 1; i < 100; i++) {
assertEquals(true, iterator.hasNext());
assertEquals(i, iterator.next());
}
assertEquals(false, iterator.hasNext());
Exception exceptionThrown = null;
try {
iterator.next();
} catch (Exception e) {
exceptionThrown = e;
}
assertTrue(exceptionThrown instanceof NoSuchElementException);
}
public void testEnumInterface()
{
Enumeration enumuration = new IterateFrom1To99();
for (int i = 1; i < 100; i++) {
assertEquals(true, enumuration.hasMoreElements());
assertEquals(i, enumuration.nextElement());
}
assertEquals(false, enumuration.hasMoreElements());
Exception exceptionThrown = null;
try {
enumuration.nextElement();
} catch (Exception e) {
exceptionThrown = e;
}
assertTrue(exceptionThrown instanceof NoSuchElementException);
}
//~ Inner Classes ----------------------------------------------------------
// This test class supplies enumeration of integer from 1 till 100.
public static class IterateFrom1To99
implements Enumeration,
Iterator
{
private int counter = 0;
private PrefetchIterator nextSupplier;
public IterateFrom1To99()
{
nextSupplier =
new PrefetchIterator<Integer>(
new PrefetchIterator.NextElementFunctor<Integer>() {
public Integer nextElement()
throws NoSuchElementException
{
counter++;
if (counter >= 100) {
throw new NoSuchElementException();
} else {
return new Integer(counter);
}
}
});
}
// forwarding to nextSupplier and return its returned value
public boolean hasMoreElements()
{
return this.nextSupplier.hasMoreElements();
}
// forwarding to nextSupplier and return its returned value
public Object nextElement()
{
return this.nextSupplier.nextElement();
}
public Object next()
{
return this.nextSupplier.next();
}
public boolean hasNext()
{
return this.nextSupplier.hasNext();
}
public void remove()
{
this.nextSupplier.remove();
}
}
}
// End PrefetchIteratorTest.java
Protects an given iterator by preventing calls to remove().
/*
* JCommon : a free general purpose class library for the Java(tm) platform
*
*
* (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ---------------------
* ReadOnlyIterator.java
* ---------------------
* (C)opyright 2003, 2004, by Thomas Morgner and Contributors.
*
* Original Author: Thomas Morgner;
* Contributor(s): -;
*
* $Id: ReadOnlyIterator.java,v 1.2 2005/10/18 13:24:19 mungady Exp $
*
* Changes
* -------------------------
* 18-Jul-2003 : Initial version
*
*/
import java.util.Iterator;
/**
* Protects an given iterator by preventing calls to remove().
*
* @author Thomas Morgner
*/
public class ReadOnlyIterator implements Iterator {
/** The base iterator which we protect. */
private Iterator base;
/**
* Creates a new read-only iterator for the given iterator.
*
* @param it the iterator.
*/
public ReadOnlyIterator(final Iterator it) {
if (it == null) {
throw new NullPointerException("Base iterator is null.");
}
this.base = it;
}
/**
* Returns <tt>true</tt> if the iteration has more elements. (In other
* words, returns <tt>true</tt> if <tt>next</tt> would return an element
* rather than throwing an exception.)
*
* @return <tt>true</tt> if the iterator has more elements.
*/
public boolean hasNext() {
return this.base.hasNext();
}
/**
* Returns the next element in the iteration.
* Throws NoSuchElementException when iteration has no more elements.
*
* @return the next element in the iteration.
*/
public Object next() {
return this.base.next();
}
/**
* Throws <code>UnsupportedOperationException</code>.
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
Sorted Iterator
/**
*
* The ObjectStyle Group Software License, version 1.1
* ObjectStyle Group - http://objectstyle.org/
*
* Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
* of the software. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if any,
* must include the following acknowlegement:
* "This product includes software developed by independent contributors
* and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
* or promote products derived from this software without prior written
* permission. For written permission, email
* "andrus at objectstyle dot org".
*
* 5. Products derived from this software may not be called "ObjectStyle"
* or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
* names without prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*
* This software consists of voluntary contributions made by many
* individuals and hosted on ObjectStyle Group web site. For more
* information on the ObjectStyle Group, please see
* <http://objectstyle.org/>.
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ruparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Contains various unorganized static utility methods used across Cayenne.
*
* @author Andrei Adamchik
*/
public class Util {
/**
* Returns a sorted iterator from an unsorted one. Use this method as a last resort,
* since it is much less efficient then just sorting a collection that backs the
* original iterator.
*/
public static Iterator sortedIterator(Iterator it, Comparator comparator) {
List list = new ArrayList();
while (it.hasNext()) {
list.add(it.next());
}
Collections.sort(list, comparator);
return list.iterator();
}
}
Treat an Iterator as an Iterable
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* @since 4.37
* @author Jaroslav Tulach
*/
public class Utils {
/**
* Treat an {@link Iterator} as an {@link Iterable} so it can be used in an enhanced for-loop.
* Bear in mind that the iterator is "consumed" by the loop and so should be used only once.
* Generally it is best to put the code which obtains the iterator inside the loop header.
* <div class="nonnormative">
* <p>Example of correct usage:</p>
* <pre>
* String text = ...;
* for (String token : NbCollections.iterable(new {@link java.util.Scanner}(text))) {
* // ...
* }
* </pre>
* </div>
* @param iterator an iterator
* @return an iterable wrapper which will traverse the iterator once
* @throws NullPointerException if the iterator is null
* @see
* @since org.openide.util 7.5
*/
public static <E> Iterable<E> iterable(final Iterator<E> iterator) {
if (iterator == null) {
throw new NullPointerException();
}
return new Iterable<E>() {
public Iterator<E> iterator() {
return iterator;
}
};
}
}
Use an Iterator and remove the item with Iterator.remove()
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String args[]) {
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("C");
list.add("C");
list.add("C");
list.add("C");
list.add("C");
for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
String s = iter.next();
if (s.equals("B")) {
iter.remove();
} else {
System.out.println(s);
}
}
for (String s : list) {
System.out.println(s);
}
}
}
Use the for-each for loop to cycle through a collection.
import java.util.ArrayList;
class ForEachDemo {
public static void main(String args[]) {
ArrayList<Integer> vals = new ArrayList<Integer>();
vals.add(1);
vals.add(2);
vals.add(3);
vals.add(4);
vals.add(5);
System.out.print("Original contents of vals: ");
for (int v : vals)
System.out.print(v + " ");
System.out.println();
int sum = 0;
for (int v : vals)
sum += v;
System.out.println("Sum of values: " + sum);
}
}