code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
/**
* Implements all iterator functions for the hashed object set.
* Subclasses may override objectAtIndex to vary the object
* returned by calls to next() (e.g. for values, and Map.Entry
* objects).
* <p/>
* <p> Note that iteration is fastest if you forego the calls to
* <tt>hasNext</tt> in favor of checking the size of the structure
* yourself and then call next() that many times:
* <p/>
* <pre>
* Iterator i = collection.iterator();
* for (int size = collection.size(); size-- > 0;) {
* Object o = i.next();
* }
* </pre>
* <p/>
* <p>You may, of course, use the hasNext(), next() idiom too if
* you aren't in a performance critical spot.</p>
*/
public interface TPrimitiveIterator extends TIterator {
/**
* Returns true if the iterator can be advanced past its current
* location.
*
* @return a <code>boolean</code> value
*/
public boolean hasNext();
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove();
} // TPrimitiveIterator
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for maps of type Object and int.
* <p/>
* The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.
* <p/>
* This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.
* <p/>
* In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.
* <p/>
* Here are some sample scenarios for this class of iterator:
* <p/>
* <pre>
* // accessing keys/values through an iterator:
* for ( TObjectIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* doSomethingWithValue( it.value() );
* }
* }
* </pre>
* <p/>
* <pre>
* // modifying values in-place through iteration:
* for ( TObjectIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.setValue( newValueForKey( it.key() ) );
* }
* }
* </pre>
* <p/>
* <pre>
* // deleting entries during iteration:
* for ( TObjectIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.remove();
* }
* }
* </pre>
* <p/>
* <pre>
* // faster iteration by avoiding hasNext():
* TObjectIntIterator iterator = map.iterator();
* for ( int i = map.size(); i-- > 0; ) {
* iterator.advance();
* doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
* }
* </pre>
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: Object_E_Iterator.template,v 1.1.2.1 2009/09/14 19:02:20 upholderoftruth Exp $
*/
public interface TObjectIntIterator<K> extends TAdvancingIterator {
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public K key();
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public int value();
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public int setValue( int val );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for maps of type int and long.
*
* <p>The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.</p>
*
* <p>This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.</p>
*
* <p>In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.</p>
*
* <p>Here are some sample scenarios for this class of iterator:</p>
*
* <pre>
* // accessing keys/values through an iterator:
* for ( TIntLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* doSomethingWithValue( it.value() );
* }
* }
* </pre>
*
* <pre>
* // modifying values in-place through iteration:
* for ( TIntLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* it.setValue( newValueForKey( it.key() ) );
* }
* }
* </pre>
*
* <pre>
* // deleting entries during iteration:
* for ( TIntLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* it.remove();
* }
* }
* </pre>
*
* <pre>
* // faster iteration by avoiding hasNext():
* TIntLongIterator iterator = map.iterator();
* for ( int i = map.size(); i-- > 0; ) {
* iterator.advance();
* doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
* }
* </pre>
*/
public interface TIntLongIterator extends TAdvancingIterator {
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public int key();
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public long value();
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public long setValue( long val );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
/**
* Common interface for all iterators used in Trove.
*/
public interface TIterator {
/**
* Returns true if the iterator can be advanced past its current location.
*
* @return a <code>boolean</code> value
*/
public boolean hasNext();
/**
* Removes the last entry returned by the iterator. The result of invoking this method
* more than once for a single entry is undefined and can leave the underlying data
* structure in a confused state.
*/
public void remove();
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for int collections.
*/
public interface TIntIterator extends TIterator {
/**
* Advances the iterator to the next element in the underlying collection
* and returns it.
*
* @return the next int in the collection
* @exception NoSuchElementException if the iterator is already exhausted
*/
public int next();
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for maps of type Object and long.
* <p/>
* The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.
* <p/>
* This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.
* <p/>
* In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.
* <p/>
* Here are some sample scenarios for this class of iterator:
* <p/>
* <pre>
* // accessing keys/values through an iterator:
* for ( TObjectLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* doSomethingWithValue( it.value() );
* }
* }
* </pre>
* <p/>
* <pre>
* // modifying values in-place through iteration:
* for ( TObjectLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.setValue( newValueForKey( it.key() ) );
* }
* }
* </pre>
* <p/>
* <pre>
* // deleting entries during iteration:
* for ( TObjectLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.remove();
* }
* }
* </pre>
* <p/>
* <pre>
* // faster iteration by avoiding hasNext():
* TObjectLongIterator iterator = map.iterator();
* for ( int i = map.size(); i-- > 0; ) {
* iterator.advance();
* doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
* }
* </pre>
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: Object_E_Iterator.template,v 1.1.2.1 2009/09/14 19:02:20 upholderoftruth Exp $
*/
public interface TObjectLongIterator<K> extends TAdvancingIterator {
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public K key();
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public long value();
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public long setValue( long val );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for maps of type int and int.
*
* <p>The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.</p>
*
* <p>This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.</p>
*
* <p>In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.</p>
*
* <p>Here are some sample scenarios for this class of iterator:</p>
*
* <pre>
* // accessing keys/values through an iterator:
* for ( TIntIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* doSomethingWithValue( it.value() );
* }
* }
* </pre>
*
* <pre>
* // modifying values in-place through iteration:
* for ( TIntIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* it.setValue( newValueForKey( it.key() ) );
* }
* }
* </pre>
*
* <pre>
* // deleting entries during iteration:
* for ( TIntIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* it.remove();
* }
* }
* </pre>
*
* <pre>
* // faster iteration by avoiding hasNext():
* TIntIntIterator iterator = map.iterator();
* for ( int i = map.size(); i-- > 0; ) {
* iterator.advance();
* doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
* }
* </pre>
*/
public interface TIntIntIterator extends TAdvancingIterator {
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public int key();
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public int value();
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public int setValue( int val );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator.hash;
import gnu.trove.impl.hash.TObjectHash;
import gnu.trove.impl.hash.THashIterator;
/**
* Iterator for hashtables that use open addressing to resolve collisions.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: TObjectHashIterator.java,v 1.1.2.4 2009/10/09 01:44:34 robeden Exp $
*/
public class TObjectHashIterator<E> extends THashIterator<E> {
protected final TObjectHash _objectHash;
public TObjectHashIterator( TObjectHash<E> hash ) {
super( hash );
_objectHash = hash;
}
@SuppressWarnings("unchecked")
protected E objectAtIndex( int index ) {
Object obj = _objectHash._set[index];
if ( obj == TObjectHash.FREE || obj == TObjectHash.REMOVED ) {
return null;
}
return (E) obj;
}
} // TObjectHashIterator
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for maps of type long and Object.
* <p/>
* The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.
* <p/>
* This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.
* <p/>
* In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.
* <p/>
* Here are some sample scenarios for this class of iterator:
* <p/>
* <pre>
* // accessing keys/values through an iterator:
* for ( TLongObjectIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* doSomethingWithValue( it.value() );
* }
* }
* </pre>
* <p/>
* <pre>
* // modifying values in-place through iteration:
* for ( TLongObjectIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.setValue( newValueForKey( it.key() ) );
* }
* }
* </pre>
* <p/>
* <pre>
* // deleting entries during iteration:
* for ( TLongObjectIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.remove();
* }
* }
* </pre>
* <p/>
* <pre>
* // faster iteration by avoiding hasNext():
* TLongObjectIterator iterator = map.iterator();
* for ( int i = map.size(); i-- > 0; ) {
* iterator.advance();
* doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
* }
* </pre>
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _E_ObjectIterator.template,v 1.1.2.1 2009/09/15 02:38:31 upholderoftruth Exp $
*/
public interface TLongObjectIterator<V> extends TAdvancingIterator {
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public long key();
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public V value();
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public V setValue( V val );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for long collections.
*/
public interface TLongIterator extends TIterator {
/**
* Advances the iterator to the next element in the underlying collection
* and returns it.
*
* @return the next long in the collection
* @exception NoSuchElementException if the iterator is already exhausted
*/
public long next();
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.set;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.iterator.TIntIterator;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.TIntCollection;
import java.util.Collection;
import java.util.Set;
import java.io.Serializable;
/**
* An implementation of the <tt>Set</tt> interface that uses an
* open-addressed hash table to store its contents.
*
* Created: Sat Nov 3 10:38:17 2001
*
* @author Eric D. Friedman, Rob Eden, Jeff Randall
* @version $Id: _E_Set.template,v 1.1.2.5 2009/09/15 02:38:31 upholderoftruth Exp $
*/
public interface TIntSet extends TIntCollection {
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
int getNoEntryValue();
/**
* Returns the number of elements in this set (its cardinality). If this
* set contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this set (its cardinality)
*/
int size();
/**
* Returns <tt>true</tt> if this set contains no elements.
*
* @return <tt>true</tt> if this set contains no elements
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this set contains the specified element.
*
* @param entry an <code>int</code> value
* @return true if the set contains the specified element.
*/
boolean contains( int entry );
/**
* Creates an iterator over the values of the set. The iterator
* supports element deletion.
*
* @return an <code>TIntIterator</code> value
*/
TIntIterator iterator();
/**
* Returns an array containing all of the elements in this set.
* If this set makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the
* elements in the same order.
*
* <p>The returned array will be "safe" in that no references to it
* are maintained by this set. (In other words, this method must
* allocate a new array even if this set is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all the elements in this set
*/
int[] toArray();
/**
* Returns an array containing elements in this set.
*
* <p>If this set fits in the specified array with room to spare
* (i.e., the array has more elements than this set), the element in
* the array immediately following the end of the set is set to
* <tt>{@link #getNoEntryValue()}</tt>. (This is useful in determining
* the length of this set <i>only</i> if the caller knows that this
* set does not contain any elements representing null.)
*
* <p>If the native array is smaller than the set size,
* the array will be filled with elements in Iterator order
* until it is full and exclude the remainder.
*
* <p>If this set makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements
* in the same order.
*
* @param dest the array into which the elements of this set are to be
* stored.
* @return an <tt>int[]</tt> containing all the elements in this set
* @throws NullPointerException if the specified array is null
*/
int[] toArray( int[] dest );
/**
* Inserts a value into the set.
*
* @param entry a <code>int</code> value
* @return true if the set was modified by the add operation
*/
boolean add( int entry );
/**
* Removes <tt>entry</tt> from the set.
*
* @param entry an <code>int</code> value
* @return true if the set was modified by the remove operation.
*/
boolean remove( int entry );
/**
* Tests the set to determine if all of the elements in
* <tt>collection</tt> are present.
*
* @param collection a <code>Collection</code> value
* @return true if all elements were present in the set.
*/
boolean containsAll( Collection<?> collection );
/**
* Tests the set to determine if all of the elements in
* <tt>TIntCollection</tt> are present.
*
* @param collection a <code>TIntCollection</code> value
* @return true if all elements were present in the set.
*/
boolean containsAll( TIntCollection collection );
/**
* Tests the set to determine if all of the elements in
* <tt>array</tt> are present.
*
* @param array as <code>array</code> of int primitives.
* @return true if all elements were present in the set.
*/
boolean containsAll( int[] array );
/**
* Adds all of the elements in <tt>collection</tt> to the set.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the add all operation.
*/
boolean addAll( Collection<? extends Integer> collection );
/**
* Adds all of the elements in the <tt>TIntCollection</tt> to the set.
*
* @param collection a <code>TIntCollection</code> value
* @return true if the set was modified by the add all operation.
*/
boolean addAll( TIntCollection collection );
/**
* Adds all of the elements in the <tt>array</tt> to the set.
*
* @param array a <code>array</code> of int primitives.
* @return true if the set was modified by the add all operation.
*/
boolean addAll( int[] array );
/**
* Removes any values in the set which are not contained in
* <tt>collection</tt>.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the retain all operation
*/
boolean retainAll( Collection<?> collection );
/**
* Removes any values in the set which are not contained in
* <tt>TIntCollection</tt>.
*
* @param collection a <code>TIntCollection</code> value
* @return true if the set was modified by the retain all operation
*/
boolean retainAll( TIntCollection collection );
/**
* Removes any values in the set which are not contained in
* <tt>array</tt>.
*
* @param array an <code>array</code> of int primitives.
* @return true if the set was modified by the retain all operation
*/
boolean retainAll( int[] array );
/**
* Removes all of the elements in <tt>collection</tt> from the set.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the remove all operation.
*/
boolean removeAll( Collection<?> collection );
/**
* Removes all of the elements in <tt>TIntCollection</tt> from the set.
*
* @param collection a <code>TIntCollection</code> value
* @return true if the set was modified by the remove all operation.
*/
boolean removeAll( TIntCollection collection );
/**
* Removes all of the elements in <tt>array</tt> from the set.
*
* @param array an <code>array</code> of int primitives.
* @return true if the set was modified by the remove all operation.
*/
public boolean removeAll( int[] array );
/**
* Empties the set.
*/
void clear();
/**
* Executes <tt>procedure</tt> for each element in the set.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
boolean forEach( TIntProcedure procedure );
// Comparison and hashing
/**
* Compares the specified object with this set for equality. Returns
* <tt>true</tt> if the specified object is also a set, the two sets
* have the same size, and every member of the specified set is
* contained in this set (or equivalently, every member of this set is
* contained in the specified set). This definition ensures that the
* equals method works properly across different implementations of the
* set interface.
*
* @param o object to be compared for equality with this set
* @return <tt>true</tt> if the specified object is equal to this set
*/
boolean equals( Object o );
/**
* Returns the hash code value for this set. The hash code of a set is
* defined to be the sum of the hash codes of the elements in the set.
* This ensures that <tt>s1.equals(s2)</tt> implies that
* <tt>s1.hashCode()==s2.hashCode()</tt> for any two sets <tt>s1</tt>
* and <tt>s2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this set
* @see Object#equals(Object)
* @see Set#equals(Object)
*/
int hashCode();
} // THashSet
| Java |
package gnu.trove.set.hash;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.iterator.hash.TObjectHashIterator;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.list.linked.TIntLinkedList;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.procedure.TObjectProcedure;
import java.io.IOException;
import java.io.ObjectOutput;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
/**
* Created by IntelliJ IDEA.
* User: Johan
* Date: 15/03/11
* Time: 18:15
* To change this template use File | Settings | File Templates.
*/
public class TLinkedHashSet<E> extends THashSet<E> {
TIntList order;
/**
* Creates a new <code>THashSet</code> instance with the default
* capacity and load factor.
*/
public TLinkedHashSet() {
}
/**
* Creates a new <code>THashSet</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TLinkedHashSet(int initialCapacity) {
super(initialCapacity);
}
/**
* Creates a new <code>THashSet</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TLinkedHashSet(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}
/**
* Creates a new <code>THashSet</code> instance containing the
* elements of <tt>collection</tt>.
*
* @param es a <code>Collection</code> value
*/
public TLinkedHashSet(Collection<? extends E> es) {
super(es);
}
/**
* initializes the Object set of this hash table.
*
* @param initialCapacity an <code>int</code> value
* @return an <code>int</code> value
*/
@Override
public int setUp(int initialCapacity) {
order = new TIntArrayList(initialCapacity) {
/**
* Grow the internal array as needed to accommodate the specified number of elements.
* The size of the array bytes on each resize unless capacity requires more than twice
* the current capacity.
*/
@Override
public void ensureCapacity(int capacity) {
if (capacity > _data.length) {
int newCap = Math.max(_set.length, capacity);
int[] tmp = new int[newCap];
System.arraycopy(_data, 0, tmp, 0, _data.length);
_data = tmp;
}
}
};
return super.setUp(initialCapacity); //To change body of overridden methods use File | Settings | File Templates.
}
/**
* Empties the set.
*/
@Override
public void clear() {
super.clear();
order.clear();
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder("{");
boolean first = true;
for (Iterator<E> it = iterator(); it.hasNext();) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append(it.next());
}
buf.append("}");
return buf.toString();
}
/**
* Inserts a value into the set.
*
* @param obj an <code>Object</code> value
* @return true if the set was modified by the add operation
*/
@Override
public boolean add(E obj) {
int index = insertKey(obj);
if (index < 0) {
return false; // already present in set, nothing to add
}
if (!order.add(index))
throw new IllegalStateException("Order not changed after insert");
postInsertHook(consumeFreeSlot);
return true; // yes, we added something
}
@Override
protected void removeAt(int index) {
// Remove from order first since super.removeAt can trigger compaction
// making the index invalid afterwards
order.remove(index);
super.removeAt(index);
}
/**
* Expands the set to accommodate new values.
*
* @param newCapacity an <code>int</code> value
*/
@Override
protected void rehash(int newCapacity) {
TIntLinkedList oldOrder = new TIntLinkedList(order);
int oldSize = size();
Object oldSet[] = _set;
order.clear();
_set = new Object[newCapacity];
Arrays.fill(_set, FREE);
for (TIntIterator iterator = oldOrder.iterator(); iterator.hasNext();) {
int i = iterator.next();
E o = (E) oldSet[i];
if (o == FREE || o == REMOVED) {
throw new IllegalStateException("Iterating over empty location while rehashing");
}
if (o != FREE && o != REMOVED) {
int index = insertKey(o);
if (index < 0) { // everyone pays for this because some people can't RTFM
throwObjectContractViolation(_set[(-index - 1)], o, size(), oldSize, oldSet);
}
if (!order.add(index))
throw new IllegalStateException("Order not changed after insert");
}
}
}
class WriteProcedure implements TIntProcedure {
final ObjectOutput output;
IOException ioException;
WriteProcedure(ObjectOutput output) {
this.output = output;
}
public IOException getIoException() {
return ioException;
}
public boolean execute(int value) {
try {
output.writeObject(_set[value]);
} catch (IOException e) {
ioException = e;
return false;
}
return true;
}
}
@Override
protected void writeEntries(ObjectOutput out) throws IOException {
// ENTRIES
WriteProcedure writeProcedure = new WriteProcedure(out);
if (!order.forEach(writeProcedure))
throw writeProcedure.getIoException();
}
/**
* Creates an iterator over the values of the set. The iterator
* supports element deletion.
*
* @return an <code>Iterator</code> value
*/
@Override
public TObjectHashIterator<E> iterator() {
return new TObjectHashIterator<E>(this) {
TIntIterator localIterator = order.iterator();
int lastIndex;
/**
* Moves the iterator to the next Object and returns it.
*
* @return an <code>Object</code> value
* @throws java.util.ConcurrentModificationException
* if the structure
* was changed using a method that isn't on this iterator.
* @throws java.util.NoSuchElementException
* if this is called on an
* exhausted iterator.
*/
@Override
public E next() {
lastIndex = localIterator.next();
return objectAtIndex(lastIndex);
}
/**
* Returns true if the iterator can be advanced past its current
* location.
*
* @return a <code>boolean</code> value
*/
@Override
public boolean hasNext() {
return localIterator.hasNext(); //To change body of overridden methods use File | Settings | File Templates.
}
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
@Override
public void remove() {
// Remove for iterator first
localIterator.remove();
// the removal within removeAt() will not change the collection
// but the localIterator will remain valid
try {
_hash.tempDisableAutoCompaction();
TLinkedHashSet.this.removeAt(lastIndex);
} finally {
_hash.reenableAutoCompaction(false);
}
}
}; //To change body of overridden methods use File | Settings | File Templates.
}
class ForEachProcedure implements TIntProcedure {
boolean changed = false;
final Object[] set;
final TObjectProcedure<? super E> procedure;
public ForEachProcedure(Object[] set, TObjectProcedure<? super E> procedure) {
this.set = set;
this.procedure = procedure;
}
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param value a value of type <code>int</code>
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute(int value) {
return procedure.execute((E) set[value]);
}
}
/**
* Executes <tt>procedure</tt> for each element in the set.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
@Override
public boolean forEach(TObjectProcedure<? super E> procedure) {
ForEachProcedure forEachProcedure = new ForEachProcedure(_set, procedure);
return order.forEach(forEachProcedure);
}
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.set.hash;
import gnu.trove.set.TLongSet;
import gnu.trove.iterator.TLongIterator;
import gnu.trove.impl.*;
import gnu.trove.impl.hash.*;
import gnu.trove.TLongCollection;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Externalizable;
import java.util.Arrays;
import java.util.Collection;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed set implementation for long primitives.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
*/
public class TLongHashSet extends TLongHash implements TLongSet, Externalizable {
static final long serialVersionUID = 1L;
/**
* Creates a new <code>TLongHashSet</code> instance with the default
* capacity and load factor.
*/
public TLongHashSet() {
super();
}
/**
* Creates a new <code>TLongHashSet</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongHashSet( int initialCapacity ) {
super( initialCapacity );
}
/**
* Creates a new <code>TIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param load_factor used to calculate the threshold over which
* rehashing takes place.
*/
public TLongHashSet( int initialCapacity, float load_factor ) {
super( initialCapacity, load_factor );
}
/**
* Creates a new <code>TLongHashSet</code> instance with a prime
* capacity equal to or greater than <tt>initial_capacity</tt> and
* with the specified load factor.
*
* @param initial_capacity an <code>int</code> value
* @param load_factor a <code>float</code> value
* @param no_entry_value a <code>long</code> value that represents null.
*/
public TLongHashSet( int initial_capacity, float load_factor,
long no_entry_value ) {
super( initial_capacity, load_factor, no_entry_value );
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TLongHashSet</code> instance that is a copy
* of the existing Collection.
*
* @param collection a <tt>Collection</tt> that will be duplicated.
*/
public TLongHashSet( Collection<? extends Long> collection ) {
this( Math.max( collection.size(), DEFAULT_CAPACITY ) );
addAll( collection );
}
/**
* Creates a new <code>TLongHashSet</code> instance that is a copy
* of the existing set.
*
* @param collection a <tt>TLongSet</tt> that will be duplicated.
*/
public TLongHashSet( TLongCollection collection ) {
this( Math.max( collection.size(), DEFAULT_CAPACITY ) );
if ( collection instanceof TLongHashSet ) {
TLongHashSet hashset = ( TLongHashSet ) collection;
this._loadFactor = hashset._loadFactor;
this.no_entry_value = hashset.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
addAll( collection );
}
/**
* Creates a new <code>TLongHashSet</code> instance containing the
* elements of <tt>array</tt>.
*
* @param array an array of <code>long</code> primitives
*/
public TLongHashSet( long[] array ) {
this( Math.max( array.length, DEFAULT_CAPACITY ) );
addAll( array );
}
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongHashIterator( this );
}
/** {@inheritDoc} */
public long[] toArray() {
long[] result = new long[ size() ];
long[] set = _set;
byte[] states = _states;
for ( int i = states.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
result[j++] = set[i];
}
}
return result;
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
long[] set = _set;
byte[] states = _states;
for ( int i = states.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
dest[j++] = set[i];
}
}
if ( dest.length > _size ) {
dest[_size] = no_entry_value;
}
return dest;
}
/** {@inheritDoc} */
public boolean add( long val ) {
int index = insertKey(val);
if ( index < 0 ) {
return false; // already present in set, nothing to add
}
postInsertHook( consumeFreeSlot );
return true; // yes, we added something
}
/** {@inheritDoc} */
public boolean remove( long val ) {
int index = index(val);
if ( index >= 0 ) {
removeAt( index );
return true;
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( ! contains( c ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( ! contains( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( int i = array.length; i-- > 0; ) {
if ( ! contains( array[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Long> collection ) {
boolean changed = false;
for ( Long element : collection ) {
long e = element.longValue();
if ( add( e ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( TLongCollection collection ) {
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( add( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( add( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove(array[i]) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
super.clear();
long[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
set[i] = no_entry_value;
states[i] = FREE;
}
}
/** {@inheritDoc} */
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
long oldSet[] = _set;
byte oldStates[] = _states;
_set = new long[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
long o = oldSet[i];
int index = insertKey(o);
}
}
}
/** {@inheritDoc} */
public boolean equals( Object other ) {
if ( ! ( other instanceof TLongSet ) ) {
return false;
}
TLongSet that = ( TLongSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
public String toString() {
StringBuilder buffy = new StringBuilder( _size * 2 + 2 );
buffy.append("{");
for ( int i = _states.length, j = 1; i-- > 0; ) {
if ( _states[i] == FULL ) {
buffy.append( _set[i] );
if ( j++ < _size ) {
buffy.append( "," );
}
}
}
buffy.append("}");
return buffy.toString();
}
class TLongHashIterator extends THashPrimitiveIterator implements TLongIterator {
/** the collection on which the iterator operates */
private final TLongHash _hash;
/** {@inheritDoc} */
public TLongHashIterator( TLongHash hash ) {
super( hash );
this._hash = hash;
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _hash._set[_index];
}
}
/** {@inheritDoc} */
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 1 );
// SUPER
super.writeExternal( out );
// NUMBER OF ENTRIES
out.writeInt( _size );
// LOAD FACTOR -- Added version 1
out.writeFloat( _loadFactor );
// NO ENTRY VALUE -- Added version 1
out.writeLong( no_entry_value );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeLong( _set[i] );
}
}
}
/** {@inheritDoc} */
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
int version = in.readByte();
// SUPER
super.readExternal( in );
// NUMBER OF ENTRIES
int size = in.readInt();
if ( version >= 1 ) {
// LOAD FACTOR
_loadFactor = in.readFloat();
// NO ENTRY VALUE
no_entry_value = in.readLong();
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
// ENTRIES
setUp( size );
while ( size-- > 0 ) {
long val = in.readLong();
add( val );
}
}
} // TIntHashSet
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.set.hash;
import gnu.trove.set.TIntSet;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.impl.*;
import gnu.trove.impl.hash.*;
import gnu.trove.TIntCollection;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Externalizable;
import java.util.Arrays;
import java.util.Collection;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed set implementation for int primitives.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
*/
public class TIntHashSet extends TIntHash implements TIntSet, Externalizable {
static final long serialVersionUID = 1L;
/**
* Creates a new <code>TIntHashSet</code> instance with the default
* capacity and load factor.
*/
public TIntHashSet() {
super();
}
/**
* Creates a new <code>TIntHashSet</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntHashSet( int initialCapacity ) {
super( initialCapacity );
}
/**
* Creates a new <code>TIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param load_factor used to calculate the threshold over which
* rehashing takes place.
*/
public TIntHashSet( int initialCapacity, float load_factor ) {
super( initialCapacity, load_factor );
}
/**
* Creates a new <code>TIntHashSet</code> instance with a prime
* capacity equal to or greater than <tt>initial_capacity</tt> and
* with the specified load factor.
*
* @param initial_capacity an <code>int</code> value
* @param load_factor a <code>float</code> value
* @param no_entry_value a <code>int</code> value that represents null.
*/
public TIntHashSet( int initial_capacity, float load_factor,
int no_entry_value ) {
super( initial_capacity, load_factor, no_entry_value );
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TIntHashSet</code> instance that is a copy
* of the existing Collection.
*
* @param collection a <tt>Collection</tt> that will be duplicated.
*/
public TIntHashSet( Collection<? extends Integer> collection ) {
this( Math.max( collection.size(), DEFAULT_CAPACITY ) );
addAll( collection );
}
/**
* Creates a new <code>TIntHashSet</code> instance that is a copy
* of the existing set.
*
* @param collection a <tt>TIntSet</tt> that will be duplicated.
*/
public TIntHashSet( TIntCollection collection ) {
this( Math.max( collection.size(), DEFAULT_CAPACITY ) );
if ( collection instanceof TIntHashSet ) {
TIntHashSet hashset = ( TIntHashSet ) collection;
this._loadFactor = hashset._loadFactor;
this.no_entry_value = hashset.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
addAll( collection );
}
/**
* Creates a new <code>TIntHashSet</code> instance containing the
* elements of <tt>array</tt>.
*
* @param array an array of <code>int</code> primitives
*/
public TIntHashSet( int[] array ) {
this( Math.max( array.length, DEFAULT_CAPACITY ) );
addAll( array );
}
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntHashIterator( this );
}
/** {@inheritDoc} */
public int[] toArray() {
int[] result = new int[ size() ];
int[] set = _set;
byte[] states = _states;
for ( int i = states.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
result[j++] = set[i];
}
}
return result;
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
int[] set = _set;
byte[] states = _states;
for ( int i = states.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
dest[j++] = set[i];
}
}
if ( dest.length > _size ) {
dest[_size] = no_entry_value;
}
return dest;
}
/** {@inheritDoc} */
public boolean add( int val ) {
int index = insertKey(val);
if ( index < 0 ) {
return false; // already present in set, nothing to add
}
postInsertHook( consumeFreeSlot );
return true; // yes, we added something
}
/** {@inheritDoc} */
public boolean remove( int val ) {
int index = index(val);
if ( index >= 0 ) {
removeAt( index );
return true;
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( ! contains( c ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( ! contains( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int i = array.length; i-- > 0; ) {
if ( ! contains( array[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Integer> collection ) {
boolean changed = false;
for ( Integer element : collection ) {
int e = element.intValue();
if ( add( e ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( TIntCollection collection ) {
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( add( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( add( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove(array[i]) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
super.clear();
int[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
set[i] = no_entry_value;
states[i] = FREE;
}
}
/** {@inheritDoc} */
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
int oldSet[] = _set;
byte oldStates[] = _states;
_set = new int[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
int o = oldSet[i];
int index = insertKey(o);
}
}
}
/** {@inheritDoc} */
public boolean equals( Object other ) {
if ( ! ( other instanceof TIntSet ) ) {
return false;
}
TIntSet that = ( TIntSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
public String toString() {
StringBuilder buffy = new StringBuilder( _size * 2 + 2 );
buffy.append("{");
for ( int i = _states.length, j = 1; i-- > 0; ) {
if ( _states[i] == FULL ) {
buffy.append( _set[i] );
if ( j++ < _size ) {
buffy.append( "," );
}
}
}
buffy.append("}");
return buffy.toString();
}
class TIntHashIterator extends THashPrimitiveIterator implements TIntIterator {
/** the collection on which the iterator operates */
private final TIntHash _hash;
/** {@inheritDoc} */
public TIntHashIterator( TIntHash hash ) {
super( hash );
this._hash = hash;
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _hash._set[_index];
}
}
/** {@inheritDoc} */
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 1 );
// SUPER
super.writeExternal( out );
// NUMBER OF ENTRIES
out.writeInt( _size );
// LOAD FACTOR -- Added version 1
out.writeFloat( _loadFactor );
// NO ENTRY VALUE -- Added version 1
out.writeInt( no_entry_value );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeInt( _set[i] );
}
}
}
/** {@inheritDoc} */
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
int version = in.readByte();
// SUPER
super.readExternal( in );
// NUMBER OF ENTRIES
int size = in.readInt();
if ( version >= 1 ) {
// LOAD FACTOR
_loadFactor = in.readFloat();
// NO ENTRY VALUE
no_entry_value = in.readInt();
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
// ENTRIES
setUp( size );
while ( size-- > 0 ) {
int val = in.readInt();
add( val );
}
}
} // TIntHashSet
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.set.hash;
import gnu.trove.impl.hash.TObjectHash;
import gnu.trove.impl.HashFunctions;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.array.ToObjectArrayProceedure;
import gnu.trove.iterator.hash.TObjectHashIterator;
import java.io.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.Arrays;
import java.lang.reflect.Array;
/**
* An implementation of the <tt>Set</tt> interface that uses an
* open-addressed hash table to store its contents.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: THashSet.java,v 1.1.2.8 2010/03/02 04:09:50 robeden Exp $
*/
public class THashSet<E> extends TObjectHash<E>
implements Set<E>, Iterable<E>, Externalizable {
static final long serialVersionUID = 1L;
/**
* Creates a new <code>THashSet</code> instance with the default
* capacity and load factor.
*/
public THashSet() {
super();
}
/**
* Creates a new <code>THashSet</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public THashSet(int initialCapacity) {
super(initialCapacity);
}
/**
* Creates a new <code>THashSet</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public THashSet(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}
/**
* Creates a new <code>THashSet</code> instance containing the
* elements of <tt>collection</tt>.
*
* @param collection a <code>Collection</code> value
*/
public THashSet(Collection<? extends E> collection) {
this(collection.size());
addAll(collection);
}
/**
* Inserts a value into the set.
*
* @param obj an <code>Object</code> value
* @return true if the set was modified by the add operation
*/
public boolean add(E obj) {
int index = insertKey(obj);
if (index < 0) {
return false; // already present in set, nothing to add
}
postInsertHook(consumeFreeSlot);
return true; // yes, we added something
}
@SuppressWarnings({"SimplifiableIfStatement"})
public boolean equals(Object other) {
if (!(other instanceof Set)) {
return false;
}
Set that = (Set) other;
if (that.size() != this.size()) {
return false;
}
return containsAll(that);
}
public int hashCode() {
HashProcedure p = new HashProcedure();
forEach(p);
return p.getHashCode();
}
private final class HashProcedure implements TObjectProcedure<E> {
private int h = 0;
public int getHashCode() {
return h;
}
public final boolean execute(E key) {
h += HashFunctions.hash(key);
return true;
}
}
/**
* Expands the set to accommodate new values.
*
* @param newCapacity an <code>int</code> value
*/
@SuppressWarnings({"unchecked"})
protected void rehash(int newCapacity) {
int oldCapacity = _set.length;
int oldSize = size();
Object oldSet[] = _set;
_set = new Object[newCapacity];
Arrays.fill(_set, FREE);
int count = 0;
for (int i = oldCapacity; i-- > 0;) {
E o = (E) oldSet[i];
if (o != FREE && o != REMOVED) {
int index = insertKey(o);
if (index < 0) { // everyone pays for this because some people can't RTFM
throwObjectContractViolation(_set[(-index - 1)], o, size(), oldSize, oldSet);
}
//
count++;
}
}
// Last check: size before and after should be the same
reportPotentialConcurrentMod(size(), oldSize);
}
/**
* Returns a new array containing the objects in the set.
*
* @return an <code>Object[]</code> value
*/
@SuppressWarnings({"unchecked"})
public Object[] toArray() {
Object[] result = new Object[size()];
forEach(new ToObjectArrayProceedure(result));
return result;
}
/**
* Returns a typed array of the objects in the set.
*
* @param a an <code>Object[]</code> value
* @return an <code>Object[]</code> value
*/
@SuppressWarnings({"unchecked"})
public <T> T[] toArray(T[] a) {
int size = size();
if (a.length < size) {
a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
}
forEach(new ToObjectArrayProceedure(a));
// If this collection fits in the specified array with room to
// spare (i.e., the array has more elements than this
// collection), the element in the array immediately following
// the end of the collection is set to null. This is useful in
// determining the length of this collection only if the
// caller knows that this collection does not contain any null
// elements.)
if (a.length > size) {
a[size] = null;
}
return a;
}
/**
* Empties the set.
*/
public void clear() {
super.clear();
Arrays.fill(_set, 0, _set.length, FREE);
}
/**
* Removes <tt>obj</tt> from the set.
*
* @param obj an <code>Object</code> value
* @return true if the set was modified by the remove operation.
*/
@SuppressWarnings({"unchecked"})
public boolean remove(Object obj) {
int index = index(obj);
if (index >= 0) {
removeAt(index);
return true;
}
return false;
}
/**
* Creates an iterator over the values of the set. The iterator
* supports element deletion.
*
* @return an <code>Iterator</code> value
*/
@SuppressWarnings({"unchecked"})
public TObjectHashIterator<E> iterator() {
return new TObjectHashIterator<E>(this);
}
/**
* Tests the set to determine if all of the elements in
* <tt>collection</tt> are present.
*
* @param collection a <code>Collection</code> value
* @return true if all elements were present in the set.
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
public boolean containsAll(Collection<?> collection) {
for (Iterator i = collection.iterator(); i.hasNext();) {
if (!contains(i.next())) {
return false;
}
}
return true;
}
/**
* Adds all of the elements in <tt>collection</tt> to the set.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the add all operation.
*/
public boolean addAll(Collection<? extends E> collection) {
boolean changed = false;
int size = collection.size();
ensureCapacity(size);
Iterator<? extends E> it = collection.iterator();
while (size-- > 0) {
if (add(it.next())) {
changed = true;
}
}
return changed;
}
/**
* Removes all of the elements in <tt>collection</tt> from the set.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the remove all operation.
*/
public boolean removeAll(Collection<?> collection) {
boolean changed = false;
int size = collection.size();
Iterator it;
it = collection.iterator();
while (size-- > 0) {
if (remove(it.next())) {
changed = true;
}
}
return changed;
}
/**
* Removes any values in the set which are not contained in
* <tt>collection</tt>.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the retain all operation
*/
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll(Collection<?> collection) {
boolean changed = false;
int size = size();
Iterator<E> it = iterator();
while (size-- > 0) {
if (!collection.contains(it.next())) {
it.remove();
changed = true;
}
}
return changed;
}
public String toString() {
final StringBuilder buf = new StringBuilder("{");
forEach(new TObjectProcedure<E>() {
private boolean first = true;
public boolean execute(Object value) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append(value);
return true;
}
});
buf.append("}");
return buf.toString();
}
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte(1);
// NOTE: Super was not written in version 0
super.writeExternal(out);
// NUMBER OF ENTRIES
out.writeInt(_size);
// ENTRIES
writeEntries(out);
}
protected void writeEntries(ObjectOutput out) throws IOException {
for (int i = _set.length; i-- > 0;) {
if (_set[i] != REMOVED && _set[i] != FREE) {
out.writeObject(_set[i]);
}
}
}
@SuppressWarnings({"unchecked"})
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
// VERSION
byte version = in.readByte();
// NOTE: super was not written in version 0
if (version != 0) {
super.readExternal(in);
}
// NUMBER OF ENTRIES
int size = in.readInt();
setUp(size);
// ENTRIES
while (size-- > 0) {
E val = (E) in.readObject();
add(val);
}
}
} // THashSet
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.set;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.iterator.TLongIterator;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.TLongCollection;
import java.util.Collection;
import java.util.Set;
import java.io.Serializable;
/**
* An implementation of the <tt>Set</tt> interface that uses an
* open-addressed hash table to store its contents.
*
* Created: Sat Nov 3 10:38:17 2001
*
* @author Eric D. Friedman, Rob Eden, Jeff Randall
* @version $Id: _E_Set.template,v 1.1.2.5 2009/09/15 02:38:31 upholderoftruth Exp $
*/
public interface TLongSet extends TLongCollection {
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
long getNoEntryValue();
/**
* Returns the number of elements in this set (its cardinality). If this
* set contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this set (its cardinality)
*/
int size();
/**
* Returns <tt>true</tt> if this set contains no elements.
*
* @return <tt>true</tt> if this set contains no elements
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this set contains the specified element.
*
* @param entry an <code>long</code> value
* @return true if the set contains the specified element.
*/
boolean contains( long entry );
/**
* Creates an iterator over the values of the set. The iterator
* supports element deletion.
*
* @return an <code>TLongIterator</code> value
*/
TLongIterator iterator();
/**
* Returns an array containing all of the elements in this set.
* If this set makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the
* elements in the same order.
*
* <p>The returned array will be "safe" in that no references to it
* are maintained by this set. (In other words, this method must
* allocate a new array even if this set is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all the elements in this set
*/
long[] toArray();
/**
* Returns an array containing elements in this set.
*
* <p>If this set fits in the specified array with room to spare
* (i.e., the array has more elements than this set), the element in
* the array immediately following the end of the set is set to
* <tt>{@link #getNoEntryValue()}</tt>. (This is useful in determining
* the length of this set <i>only</i> if the caller knows that this
* set does not contain any elements representing null.)
*
* <p>If the native array is smaller than the set size,
* the array will be filled with elements in Iterator order
* until it is full and exclude the remainder.
*
* <p>If this set makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements
* in the same order.
*
* @param dest the array into which the elements of this set are to be
* stored.
* @return an <tt>long[]</tt> containing all the elements in this set
* @throws NullPointerException if the specified array is null
*/
long[] toArray( long[] dest );
/**
* Inserts a value into the set.
*
* @param entry a <code>long</code> value
* @return true if the set was modified by the add operation
*/
boolean add( long entry );
/**
* Removes <tt>entry</tt> from the set.
*
* @param entry an <code>long</code> value
* @return true if the set was modified by the remove operation.
*/
boolean remove( long entry );
/**
* Tests the set to determine if all of the elements in
* <tt>collection</tt> are present.
*
* @param collection a <code>Collection</code> value
* @return true if all elements were present in the set.
*/
boolean containsAll( Collection<?> collection );
/**
* Tests the set to determine if all of the elements in
* <tt>TLongCollection</tt> are present.
*
* @param collection a <code>TLongCollection</code> value
* @return true if all elements were present in the set.
*/
boolean containsAll( TLongCollection collection );
/**
* Tests the set to determine if all of the elements in
* <tt>array</tt> are present.
*
* @param array as <code>array</code> of long primitives.
* @return true if all elements were present in the set.
*/
boolean containsAll( long[] array );
/**
* Adds all of the elements in <tt>collection</tt> to the set.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the add all operation.
*/
boolean addAll( Collection<? extends Long> collection );
/**
* Adds all of the elements in the <tt>TLongCollection</tt> to the set.
*
* @param collection a <code>TLongCollection</code> value
* @return true if the set was modified by the add all operation.
*/
boolean addAll( TLongCollection collection );
/**
* Adds all of the elements in the <tt>array</tt> to the set.
*
* @param array a <code>array</code> of long primitives.
* @return true if the set was modified by the add all operation.
*/
boolean addAll( long[] array );
/**
* Removes any values in the set which are not contained in
* <tt>collection</tt>.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the retain all operation
*/
boolean retainAll( Collection<?> collection );
/**
* Removes any values in the set which are not contained in
* <tt>TLongCollection</tt>.
*
* @param collection a <code>TLongCollection</code> value
* @return true if the set was modified by the retain all operation
*/
boolean retainAll( TLongCollection collection );
/**
* Removes any values in the set which are not contained in
* <tt>array</tt>.
*
* @param array an <code>array</code> of long primitives.
* @return true if the set was modified by the retain all operation
*/
boolean retainAll( long[] array );
/**
* Removes all of the elements in <tt>collection</tt> from the set.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the remove all operation.
*/
boolean removeAll( Collection<?> collection );
/**
* Removes all of the elements in <tt>TLongCollection</tt> from the set.
*
* @param collection a <code>TLongCollection</code> value
* @return true if the set was modified by the remove all operation.
*/
boolean removeAll( TLongCollection collection );
/**
* Removes all of the elements in <tt>array</tt> from the set.
*
* @param array an <code>array</code> of long primitives.
* @return true if the set was modified by the remove all operation.
*/
public boolean removeAll( long[] array );
/**
* Empties the set.
*/
void clear();
/**
* Executes <tt>procedure</tt> for each element in the set.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
boolean forEach( TLongProcedure procedure );
// Comparison and hashing
/**
* Compares the specified object with this set for equality. Returns
* <tt>true</tt> if the specified object is also a set, the two sets
* have the same size, and every member of the specified set is
* contained in this set (or equivalently, every member of this set is
* contained in the specified set). This definition ensures that the
* equals method works properly across different implementations of the
* set interface.
*
* @param o object to be compared for equality with this set
* @return <tt>true</tt> if the specified object is equal to this set
*/
boolean equals( Object o );
/**
* Returns the hash code value for this set. The hash code of a set is
* defined to be the sum of the hash codes of the elements in the set.
* This ensures that <tt>s1.equals(s2)</tt> implies that
* <tt>s1.hashCode()==s2.hashCode()</tt> for any two sets <tt>s1</tt>
* and <tt>s2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this set
* @see Object#equals(Object)
* @see Set#equals(Object)
*/
int hashCode();
} // THashSet
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.function.*;
import gnu.trove.iterator.*;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.TIntCollection;
import java.util.Map;
import java.io.Serializable;
/**
* Interface for a primitive map of int keys and int values.
*/
public interface TIntIntMap {
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null key in this collection.
*/
public int getNoEntryKey();
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
public int getNoEntryValue();
/**
* Inserts a key/value pair into the map.
*
* @param key an <code>int</code> value
* @param value an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int put( int key, int value );
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key an <code>int</code> value
* @param value an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int putIfAbsent( int key, int value );
/**
* Put all the entries from the given Map into this map.
*
* @param map The Map from which entries will be obtained to put into this map.
*/
public void putAll( Map<? extends Integer, ? extends Integer> map );
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
public void putAll( TIntIntMap map );
/**
* Retrieves the value for <tt>key</tt>
*
* @param key an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int get( int key );
/**
* Empties the map.
*/
public void clear();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
public boolean isEmpty();
/**
* Deletes a key/value pair from the map.
*
* @param key an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int remove( int key );
/**
* Returns an <tt>int</tt> value that is the number of elements in the map.
*
* @return an <tt>int</tt> value that is the number of elements in the map.
*/
public int size();
/**
* Returns the keys of the map as a <tt>TIntSet</tt>
*
* @return the keys of the map as a <tt>TIntSet</tt>
*/
public TIntSet keySet();
/**
* Returns the keys of the map as an array of <tt>int</tt> values.
*
* @return the keys of the map as an array of <tt>int</tt> values.
*/
public int[] keys();
/**
* Returns the keys of the map.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
public int[] keys( int[] array );
/**
* Returns the values of the map as a <tt>TIntCollection</tt>
*
* @return the values of the map as a <tt>TIntCollection</tt>
*/
public TIntCollection valueCollection();
/**
* Returns the values of the map as an array of <tt>#e#</tt> values.
*
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public int[] values();
/**
* Returns the values of the map using an existing array.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public int[] values( int[] array );
/**
* Checks for the presence of <tt>val</tt> in the values of the map.
*
* @param val an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean containsValue( int val );
/**
* Checks for the present of <tt>key</tt> in the keys of the map.
*
* @param key an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean containsKey( int key );
/**
* @return a TIntIntIterator with access to this map's keys and values
*/
public TIntIntIterator iterator();
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TIntProcedure procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>T#F#Procedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TIntProcedure procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOIntIntProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TIntIntProcedure procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TIntFunction</code> value
*/
public void transformValues( TIntFunction function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TIntIntProcedure procedure );
/**
* Increments the primitive value mapped to key by 1
*
* @param key the key of the value to increment
* @return true if a mapping was found and modified.
*/
public boolean increment( int key );
/**
* Adjusts the primitive value mapped to key.
*
* @param key the key of the value to increment
* @param amount the amount to adjust the value by.
* @return true if a mapping was found and modified.
*/
public boolean adjustValue( int key, int amount );
/**
* Adjusts the primitive value mapped to the key if the key is present in the map.
* Otherwise, the <tt>initial_value</tt> is put in the map.
*
* @param key the key of the value to increment
* @param adjust_amount the amount to adjust the value by
* @param put_amount the value put into the map if the key is not initial present
*
* @return the value present in the map after the adjustment or put operation
*/
public int adjustOrPutValue( int key, int adjust_amount, int put_amount );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.function.*;
import gnu.trove.iterator.*;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.TIntCollection;
import java.util.Map;
import java.io.Serializable;
/**
* Interface for a primitive map of long keys and int values.
*/
public interface TLongIntMap {
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null key in this collection.
*/
public long getNoEntryKey();
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
public int getNoEntryValue();
/**
* Inserts a key/value pair into the map.
*
* @param key an <code>long</code> value
* @param value an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int put( long key, int value );
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key an <code>long</code> value
* @param value an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int putIfAbsent( long key, int value );
/**
* Put all the entries from the given Map into this map.
*
* @param map The Map from which entries will be obtained to put into this map.
*/
public void putAll( Map<? extends Long, ? extends Integer> map );
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
public void putAll( TLongIntMap map );
/**
* Retrieves the value for <tt>key</tt>
*
* @param key an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int get( long key );
/**
* Empties the map.
*/
public void clear();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
public boolean isEmpty();
/**
* Deletes a key/value pair from the map.
*
* @param key an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int remove( long key );
/**
* Returns an <tt>int</tt> value that is the number of elements in the map.
*
* @return an <tt>int</tt> value that is the number of elements in the map.
*/
public int size();
/**
* Returns the keys of the map as a <tt>TLongSet</tt>
*
* @return the keys of the map as a <tt>TLongSet</tt>
*/
public TLongSet keySet();
/**
* Returns the keys of the map as an array of <tt>long</tt> values.
*
* @return the keys of the map as an array of <tt>long</tt> values.
*/
public long[] keys();
/**
* Returns the keys of the map.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
public long[] keys( long[] array );
/**
* Returns the values of the map as a <tt>TIntCollection</tt>
*
* @return the values of the map as a <tt>TIntCollection</tt>
*/
public TIntCollection valueCollection();
/**
* Returns the values of the map as an array of <tt>#e#</tt> values.
*
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public int[] values();
/**
* Returns the values of the map using an existing array.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public int[] values( int[] array );
/**
* Checks for the presence of <tt>val</tt> in the values of the map.
*
* @param val an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean containsValue( int val );
/**
* Checks for the present of <tt>key</tt> in the keys of the map.
*
* @param key an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean containsKey( long key );
/**
* @return a TLongIntIterator with access to this map's keys and values
*/
public TLongIntIterator iterator();
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TLongProcedure procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>T#F#Procedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TIntProcedure procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOLongIntProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TLongIntProcedure procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TIntFunction</code> value
*/
public void transformValues( TIntFunction function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TLongIntProcedure procedure );
/**
* Increments the primitive value mapped to key by 1
*
* @param key the key of the value to increment
* @return true if a mapping was found and modified.
*/
public boolean increment( long key );
/**
* Adjusts the primitive value mapped to key.
*
* @param key the key of the value to increment
* @param amount the amount to adjust the value by.
* @return true if a mapping was found and modified.
*/
public boolean adjustValue( long key, int amount );
/**
* Adjusts the primitive value mapped to the key if the key is present in the map.
* Otherwise, the <tt>initial_value</tt> is put in the map.
*
* @param key the key of the value to increment
* @param adjust_amount the amount to adjust the value by
* @param put_amount the value put into the map if the key is not initial present
*
* @return the value present in the map after the adjustment or put operation
*/
public int adjustOrPutValue( long key, int adjust_amount, int put_amount );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.function.*;
import gnu.trove.iterator.*;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.TLongCollection;
import java.util.Map;
import java.io.Serializable;
/**
* Interface for a primitive map of long keys and long values.
*/
public interface TLongLongMap {
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null key in this collection.
*/
public long getNoEntryKey();
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
public long getNoEntryValue();
/**
* Inserts a key/value pair into the map.
*
* @param key an <code>long</code> value
* @param value an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long put( long key, long value );
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key an <code>long</code> value
* @param value an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long putIfAbsent( long key, long value );
/**
* Put all the entries from the given Map into this map.
*
* @param map The Map from which entries will be obtained to put into this map.
*/
public void putAll( Map<? extends Long, ? extends Long> map );
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
public void putAll( TLongLongMap map );
/**
* Retrieves the value for <tt>key</tt>
*
* @param key an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long get( long key );
/**
* Empties the map.
*/
public void clear();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
public boolean isEmpty();
/**
* Deletes a key/value pair from the map.
*
* @param key an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long remove( long key );
/**
* Returns an <tt>int</tt> value that is the number of elements in the map.
*
* @return an <tt>int</tt> value that is the number of elements in the map.
*/
public int size();
/**
* Returns the keys of the map as a <tt>TLongSet</tt>
*
* @return the keys of the map as a <tt>TLongSet</tt>
*/
public TLongSet keySet();
/**
* Returns the keys of the map as an array of <tt>long</tt> values.
*
* @return the keys of the map as an array of <tt>long</tt> values.
*/
public long[] keys();
/**
* Returns the keys of the map.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
public long[] keys( long[] array );
/**
* Returns the values of the map as a <tt>TLongCollection</tt>
*
* @return the values of the map as a <tt>TLongCollection</tt>
*/
public TLongCollection valueCollection();
/**
* Returns the values of the map as an array of <tt>#e#</tt> values.
*
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public long[] values();
/**
* Returns the values of the map using an existing array.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public long[] values( long[] array );
/**
* Checks for the presence of <tt>val</tt> in the values of the map.
*
* @param val an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean containsValue( long val );
/**
* Checks for the present of <tt>key</tt> in the keys of the map.
*
* @param key an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean containsKey( long key );
/**
* @return a TLongLongIterator with access to this map's keys and values
*/
public TLongLongIterator iterator();
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TLongProcedure procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>T#F#Procedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TLongProcedure procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOLongLongProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TLongLongProcedure procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TLongFunction</code> value
*/
public void transformValues( TLongFunction function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TLongLongProcedure procedure );
/**
* Increments the primitive value mapped to key by 1
*
* @param key the key of the value to increment
* @return true if a mapping was found and modified.
*/
public boolean increment( long key );
/**
* Adjusts the primitive value mapped to key.
*
* @param key the key of the value to increment
* @param amount the amount to adjust the value by.
* @return true if a mapping was found and modified.
*/
public boolean adjustValue( long key, long amount );
/**
* Adjusts the primitive value mapped to the key if the key is present in the map.
* Otherwise, the <tt>initial_value</tt> is put in the map.
*
* @param key the key of the value to increment
* @param adjust_amount the amount to adjust the value by
* @param put_amount the value put into the map if the key is not initial present
*
* @return the value present in the map after the adjustment or put operation
*/
public long adjustOrPutValue( long key, long adjust_amount, long put_amount );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
import gnu.trove.iterator.TLongObjectIterator;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.TLongObjectProcedure;
import gnu.trove.function.TObjectFunction;
import gnu.trove.set.TLongSet;
import java.util.Collection;
import java.util.Map;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for a primitive map of long keys and Object values.
*/
public interface TLongObjectMap<V> {
// Query Operations
/**
* Returns the value that represents null in the {@link #keySet()}.
* The default value is generally zero, but can be changed during
* construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
long getNoEntryKey();
/**
* Returns the number of key-value mappings in this map. If the
* map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of key-value mappings in this map
*/
int size();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this map contains a mapping for the specified
* key. More formally, returns <tt>true</tt> if and only if
* this map contains a mapping for a key <tt>k</tt> such that
* <tt>key.equals(k)</tt>. (There can be at most one such mapping.)
*
* @param key key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
boolean containsKey( long key );
/**
* Returns <tt>true</tt> if this map maps one or more keys to the
* specified value. More formally, returns <tt>true</tt> if and only if
* this map contains at least one mapping to a value <tt>v</tt> such that
* <tt>(value==null ? v==null : value.equals(v))</tt>. This operation
* will probably require time linear in the map size for most
* implementations of the <tt>Map</tt> interface.
*
* @param value value whose presence in this map is to be tested
* @return <tt>true</tt> if this map maps one or more keys to the
* specified value
* @throws ClassCastException if the value is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified value is null and this
* map does not permit null values (optional)
*/
boolean containsValue( Object value );
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>If this map permits null values, then a return value of
* {@code null} does not <i>necessarily</i> indicate that the map
* contains no mapping for the key; it's also possible that the map
* explicitly maps the key to {@code null}. The {@link #containsKey
* containsKey} operation may be used to distinguish these two cases.
*
* @param key the key whose associated value is to be returned
* @return the <tt>long</tt> value to which the specified key is mapped, or
* {@code null} if this map contains no mapping for the key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
V get( long key );
// Modification Operations
/**
* Associates the specified value with the specified key in this map
* (optional operation). If the map previously contained a mapping for
* the key, the old value is replaced by the specified value. (A map
* <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
* if {@link #containsKey(long) m.containsKey(k)} would return
* <tt>true</tt>.)
*
* @param key key with which the specified value is to be associated
* @param value an <tt>long</tt> value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>no_entry_value</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>no_entry_value</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>,
* if the implementation supports <tt>null</tt> values.)
* @throws UnsupportedOperationException if the <tt>put</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* @throws NullPointerException if the specified key or value is null
* and this map does not permit null keys or values
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* @see #getNoEntryKey()
*/
V put( long key, V value);
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key key with which the specified value is to be associated
* @param value an <tt>long</tt> value to be associated with the specified key
*
* @return the previous value associated with <tt>key</tt>, or null
* if none was found.
*/
V putIfAbsent( long key, V value );
/**
* Removes the mapping for a key from this map if it is present
* (optional operation). More formally, if this map contains a mapping
* from key <tt>k</tt> to value <tt>v</tt> such that
* <code>key.equals(k)</code>, that mapping
* is removed. (The map can contain at most one such mapping.)
*
* <p>Returns the value to which this map previously associated the key,
* or <tt>null</tt> if the map contained no mapping for the key.
*
* <p>If this map permits null values, then a return value of
* <tt>null</tt> does not <i>necessarily</i> indicate that the map
* contained no mapping for the key; it's also possible that the map
* explicitly mapped the key to <tt>null</tt>.
*
* <p>The map will not contain a mapping for the specified key once the
* call returns.
*
* @param key key whose mapping is to be removed from the map
* @return the previous <tt>long</tt> value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this map
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this
* map does not permit null keys (optional)
*/
V remove( long key );
// Bulk Operations
/**
* Copies all of the mappings from the specified map to this map
* (optional operation). The effect of this call is equivalent to that
* of calling {@link #put(long,Object) put(k, v)} on this map once
* for each mapping from key <tt>k</tt> to value <tt>v</tt> in the
* specified map. The behavior of this operation is undefined if the
* specified map is modified while the operation is in progress.
*
* @param m mappings to be stored in this map
* @throws UnsupportedOperationException if the <tt>putAll</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of a key or value in the
* specified map prevents it from being stored in this map
* @throws NullPointerException if the specified map is null, or if
* this map does not permit null keys or values, and the
* specified map contains null keys or values
* @throws IllegalArgumentException if some property of a key or value in
* the specified map prevents it from being stored in this map
*/
void putAll( Map<? extends Long, ? extends V> m);
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
void putAll( TLongObjectMap<? extends V> map );
/**
* Removes all of the mappings from this map (optional operation).
* The map will be empty after this call returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this map
*/
void clear();
// Views
/**
* Returns a {@link TLongSet} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*
* @return a set view of the keys contained in this map
*/
TLongSet keySet();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @return a copy of the keys of the map as an array.
*/
long[] keys();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
long[] keys( long[] array );
/**
* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own <tt>remove</tt> operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>Iterator.remove</tt>,
* <tt>Collection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a collection view of the values contained in this map
*/
Collection<V> valueCollection();
/**
* Returns the values of the map as an array of <tt>long</tt> values.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @return the values of the map as an array of <tt>long</tt> values.
*/
V[] values();
/**
* Returns the values of the map using an existing array.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>long</tt> values.
*/
V[] values( V[] array );
/**
* Returns a <tt>TLongObjectIterator</tt> with access to this map's keys and values.
*
* @return a <tt>TLongObjectIterator</tt> with access to this map's keys and values.
*/
public TLongObjectIterator<V> iterator();
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TLongProcedure procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TObjectProcedure<? super V> procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TLongObjectProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TLongObjectProcedure<? super V> procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TObjectFunction</code> value
*/
public void transformValues( TObjectFunction<V,V> function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TLongObjectProcedure<? super V> procedure );
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
boolean equals( Object o );
/**
* Returns the hash code value for this map. The hash code of a map is
* defined to be the sum of the hash codes of each entry in the map's
* <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
* implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
* <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this map
* @see Object#equals(Object)
* @see #equals(Object)
*/
int hashCode();
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.map.TIntIntMap;
import gnu.trove.function.TIntFunction;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.iterator.*;
import gnu.trove.iterator.hash.*;
import gnu.trove.impl.hash.*;
import gnu.trove.impl.HashFunctions;
import gnu.trove.*;
import java.io.*;
import java.util.*;
/**
* An open addressed Map implementation for int keys and int values.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_HashMap.template,v 1.1.2.16 2010/03/02 04:09:50 robeden Exp $
*/
public class TIntIntHashMap extends TIntIntHash implements TIntIntMap, Externalizable {
static final long serialVersionUID = 1L;
/** the values of the map */
protected transient int[] _values;
/**
* Creates a new <code>TIntIntHashMap</code> instance with the default
* capacity and load factor.
*/
public TIntIntHashMap() {
super();
}
/**
* Creates a new <code>TIntIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntIntHashMap( int initialCapacity ) {
super( initialCapacity );
}
/**
* Creates a new <code>TIntIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TIntIntHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
}
/**
* Creates a new <code>TIntIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
* @param noEntryKey a <code>int</code> value that represents
* <tt>null</tt> for the Key set.
* @param noEntryValue a <code>int</code> value that represents
* <tt>null</tt> for the Value set.
*/
public TIntIntHashMap( int initialCapacity, float loadFactor,
int noEntryKey, int noEntryValue ) {
super( initialCapacity, loadFactor, noEntryKey, noEntryValue );
}
/**
* Creates a new <code>TIntIntHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param keys a <tt>int</tt> array containing the keys for the matching values.
* @param values a <tt>int</tt> array containing the values.
*/
public TIntIntHashMap( int[] keys, int[] values ) {
super( Math.max( keys.length, values.length ) );
int size = Math.min( keys.length, values.length );
for ( int i = 0; i < size; i++ ) {
this.put( keys[i], values[i] );
}
}
/**
* Creates a new <code>TIntIntHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param map a <tt>TIntIntMap</tt> that will be duplicated.
*/
public TIntIntHashMap( TIntIntMap map ) {
super( map.size() );
if ( map instanceof TIntIntHashMap ) {
TIntIntHashMap hashmap = ( TIntIntHashMap ) map;
this._loadFactor = hashmap._loadFactor;
this.no_entry_key = hashmap.no_entry_key;
this.no_entry_value = hashmap.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_key != ( int ) 0 ) {
Arrays.fill( _set, this.no_entry_key );
}
//noinspection RedundantCast
if ( this.no_entry_value != ( int ) 0 ) {
Arrays.fill( _values, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
putAll( map );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = new int[capacity];
return capacity;
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
/** {@inheritDoc} */
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
int oldKeys[] = _set;
int oldVals[] = _values;
byte oldStates[] = _states;
_set = new int[newCapacity];
_values = new int[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
int o = oldKeys[i];
int index = insertKey( o );
_values[index] = oldVals[i];
}
}
}
/** {@inheritDoc} */
public int put( int key, int value ) {
int index = insertKey( key );
return doPut( key, value, index );
}
/** {@inheritDoc} */
public int putIfAbsent( int key, int value ) {
int index = insertKey( key );
if (index < 0)
return _values[-index - 1];
return doPut( key, value, index );
}
private int doPut( int key, int value, int index ) {
int previous = no_entry_value;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public void putAll( Map<? extends Integer, ? extends Integer> map ) {
ensureCapacity( map.size() );
// could optimize this for cases when map instanceof THashMap
for ( Map.Entry<? extends Integer, ? extends Integer> entry : map.entrySet() ) {
this.put( entry.getKey().intValue(), entry.getValue().intValue() );
}
}
/** {@inheritDoc} */
public void putAll( TIntIntMap map ) {
ensureCapacity( map.size() );
TIntIntIterator iter = map.iterator();
while ( iter.hasNext() ) {
iter.advance();
this.put( iter.key(), iter.value() );
}
}
/** {@inheritDoc} */
public int get( int key ) {
int index = index( key );
return index < 0 ? no_entry_value : _values[index];
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, no_entry_key );
Arrays.fill( _values, 0, _values.length, no_entry_value );
Arrays.fill( _states, 0, _states.length, FREE );
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public int remove( int key ) {
int prev = no_entry_value;
int index = index( key );
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/** {@inheritDoc} */
protected void removeAt( int index ) {
_values[index] = no_entry_value;
super.removeAt( index ); // clear key, state; adjust size
}
/** {@inheritDoc} */
public TIntSet keySet() {
return new TKeyView();
}
/** {@inheritDoc} */
public int[] keys() {
int[] keys = new int[size()];
int[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
keys[j++] = k[i];
}
}
return keys;
}
/** {@inheritDoc} */
public int[] keys( int[] array ) {
int size = size();
if ( array.length < size ) {
array = new int[size];
}
int[] keys = _set;
byte[] states = _states;
for ( int i = keys.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = keys[i];
}
}
return array;
}
/** {@inheritDoc} */
public TIntCollection valueCollection() {
return new TValueView();
}
/** {@inheritDoc} */
public int[] values() {
int[] vals = new int[size()];
int[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
public int[] values( int[] array ) {
int size = size();
if ( array.length < size ) {
array = new int[size];
}
int[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = v[i];
}
}
return array;
}
/** {@inheritDoc} */
public boolean containsValue( int val ) {
byte[] states = _states;
int[] vals = _values;
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && val == vals[i] ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsKey( int key ) {
return contains( key );
}
/** {@inheritDoc} */
public TIntIntIterator iterator() {
return new TIntIntHashIterator( this );
}
/** {@inheritDoc} */
public boolean forEachKey( TIntProcedure procedure ) {
return forEach( procedure );
}
/** {@inheritDoc} */
public boolean forEachValue( TIntProcedure procedure ) {
byte[] states = _states;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean forEachEntry( TIntIntProcedure procedure ) {
byte[] states = _states;
int[] keys = _set;
int[] values = _values;
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public void transformValues( TIntFunction function ) {
byte[] states = _states;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
values[i] = function.execute( values[i] );
}
}
}
/** {@inheritDoc} */
public boolean retainEntries( TIntIntProcedure procedure ) {
boolean modified = false;
byte[] states = _states;
int[] keys = _set;
int[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
removeAt( i );
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/** {@inheritDoc} */
public boolean increment( int key ) {
return adjustValue( key, ( int ) 1 );
}
/** {@inheritDoc} */
public boolean adjustValue( int key, int amount ) {
int index = index( key );
if (index < 0) {
return false;
} else {
_values[index] += amount;
return true;
}
}
/** {@inheritDoc} */
public int adjustOrPutValue( int key, int adjust_amount, int put_amount ) {
int index = insertKey( key );
final boolean isNewMapping;
final int newValue;
if ( index < 0 ) {
index = -index -1;
newValue = ( _values[index] += adjust_amount );
isNewMapping = false;
} else {
newValue = ( _values[index] = put_amount );
isNewMapping = true;
}
byte previousState = _states[index];
if ( isNewMapping ) {
postInsertHook(consumeFreeSlot);
}
return newValue;
}
/** a view onto the keys of the map. */
protected class TKeyView implements TIntSet {
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntIntKeyHashIterator( TIntIntHashMap.this );
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_key;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( int entry ) {
return TIntIntHashMap.this.contains( entry );
}
/** {@inheritDoc} */
public int[] toArray() {
return TIntIntHashMap.this.keys();
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
return TIntIntHashMap.this.keys( dest );
}
/**
* Unsupported when operating upon a Key Set view of a TIntIntMap
* <p/>
* {@inheritDoc}
*/
public boolean add( int entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( int entry ) {
return no_entry_value != TIntIntHashMap.this.remove( entry );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int ele = ( ( Integer ) element ).intValue();
if ( ! TIntIntHashMap.this.containsKey( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TIntIntHashMap.this.containsKey( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int element : array ) {
if ( ! TIntIntHashMap.this.contains( element ) ) {
return false;
}
}
return true;
}
/**
* Unsupported when operating upon a Key Set view of a TIntIntMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( Collection<? extends Integer> collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TIntIntMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( TIntCollection collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TIntIntMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( int[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TIntIntHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
return TIntIntHashMap.this.forEachKey( procedure );
}
@Override
public boolean equals( Object other ) {
if (! (other instanceof TIntSet)) {
return false;
}
final TIntSet that = ( TIntSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachKey( new TIntProcedure() {
private boolean first = true;
public boolean execute( int key ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( key );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
/** a view onto the values of the map. */
protected class TValueView implements TIntCollection {
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntIntValueHashIterator( TIntIntHashMap.this );
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( int entry ) {
return TIntIntHashMap.this.containsValue( entry );
}
/** {@inheritDoc} */
public int[] toArray() {
return TIntIntHashMap.this.values();
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
return TIntIntHashMap.this.values( dest );
}
public boolean add( int entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( int entry ) {
int[] values = _values;
int[] set = _set;
for ( int i = values.length; i-- > 0; ) {
if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) {
removeAt( i );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int ele = ( ( Integer ) element ).intValue();
if ( ! TIntIntHashMap.this.containsValue( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TIntIntHashMap.this.containsValue( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int element : array ) {
if ( ! TIntIntHashMap.this.containsValue( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Integer> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TIntCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( int[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, values[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TIntIntHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
return TIntIntHashMap.this.forEachValue( procedure );
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachValue( new TIntProcedure() {
private boolean first = true;
public boolean execute( int value ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( value );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
class TIntIntKeyHashIterator extends THashPrimitiveIterator implements TIntIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TIntIntKeyHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _set[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TIntIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TIntIntValueHashIterator extends THashPrimitiveIterator implements TIntIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TIntIntValueHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _values[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TIntIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TIntIntHashIterator extends THashPrimitiveIterator implements TIntIntIterator {
/**
* Creates an iterator over the specified map
*
* @param map the <tt>TIntIntHashMap</tt> we will be iterating over.
*/
TIntIntHashIterator( TIntIntHashMap map ) {
super( map );
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
public int key() {
return _set[_index];
}
/** {@inheritDoc} */
public int value() {
return _values[_index];
}
/** {@inheritDoc} */
public int setValue( int val ) {
int old = value();
_values[_index] = val;
return old;
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TIntIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
/** {@inheritDoc} */
@Override
public boolean equals( Object other ) {
if ( ! ( other instanceof TIntIntMap ) ) {
return false;
}
TIntIntMap that = ( TIntIntMap ) other;
if ( that.size() != this.size() ) {
return false;
}
int[] values = _values;
byte[] states = _states;
int this_no_entry_value = getNoEntryValue();
int that_no_entry_value = that.getNoEntryValue();
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
int key = _set[i];
int that_value = that.get( key );
int this_value = values[i];
if ( ( this_value != that_value ) &&
( this_value != this_no_entry_value ) &&
( that_value != that_no_entry_value ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int hashcode = 0;
byte[] states = _states;
for ( int i = _values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] ) ^
HashFunctions.hash( _values[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachEntry( new TIntIntProcedure() {
private boolean first = true;
public boolean execute( int key, int value ) {
if ( first ) first = false;
else buf.append( ", " );
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append( "}" );
return buf.toString();
}
/** {@inheritDoc} */
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeInt( _set[i] );
out.writeInt( _values[i] );
}
}
}
/** {@inheritDoc} */
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
int key = in.readInt();
int val = in.readInt();
put(key, val);
}
}
} // TIntIntHashMap
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.map.TLongLongMap;
import gnu.trove.function.TLongFunction;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.iterator.*;
import gnu.trove.iterator.hash.*;
import gnu.trove.impl.hash.*;
import gnu.trove.impl.HashFunctions;
import gnu.trove.*;
import java.io.*;
import java.util.*;
/**
* An open addressed Map implementation for long keys and long values.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_HashMap.template,v 1.1.2.16 2010/03/02 04:09:50 robeden Exp $
*/
public class TLongLongHashMap extends TLongLongHash implements TLongLongMap, Externalizable {
static final long serialVersionUID = 1L;
/** the values of the map */
protected transient long[] _values;
/**
* Creates a new <code>TLongLongHashMap</code> instance with the default
* capacity and load factor.
*/
public TLongLongHashMap() {
super();
}
/**
* Creates a new <code>TLongLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongLongHashMap( int initialCapacity ) {
super( initialCapacity );
}
/**
* Creates a new <code>TLongLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TLongLongHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
}
/**
* Creates a new <code>TLongLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
* @param noEntryKey a <code>long</code> value that represents
* <tt>null</tt> for the Key set.
* @param noEntryValue a <code>long</code> value that represents
* <tt>null</tt> for the Value set.
*/
public TLongLongHashMap( int initialCapacity, float loadFactor,
long noEntryKey, long noEntryValue ) {
super( initialCapacity, loadFactor, noEntryKey, noEntryValue );
}
/**
* Creates a new <code>TLongLongHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param keys a <tt>long</tt> array containing the keys for the matching values.
* @param values a <tt>long</tt> array containing the values.
*/
public TLongLongHashMap( long[] keys, long[] values ) {
super( Math.max( keys.length, values.length ) );
int size = Math.min( keys.length, values.length );
for ( int i = 0; i < size; i++ ) {
this.put( keys[i], values[i] );
}
}
/**
* Creates a new <code>TLongLongHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param map a <tt>TLongLongMap</tt> that will be duplicated.
*/
public TLongLongHashMap( TLongLongMap map ) {
super( map.size() );
if ( map instanceof TLongLongHashMap ) {
TLongLongHashMap hashmap = ( TLongLongHashMap ) map;
this._loadFactor = hashmap._loadFactor;
this.no_entry_key = hashmap.no_entry_key;
this.no_entry_value = hashmap.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_key != ( long ) 0 ) {
Arrays.fill( _set, this.no_entry_key );
}
//noinspection RedundantCast
if ( this.no_entry_value != ( long ) 0 ) {
Arrays.fill( _values, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
putAll( map );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = new long[capacity];
return capacity;
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
/** {@inheritDoc} */
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
long oldKeys[] = _set;
long oldVals[] = _values;
byte oldStates[] = _states;
_set = new long[newCapacity];
_values = new long[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
long o = oldKeys[i];
int index = insertKey( o );
_values[index] = oldVals[i];
}
}
}
/** {@inheritDoc} */
public long put( long key, long value ) {
int index = insertKey( key );
return doPut( key, value, index );
}
/** {@inheritDoc} */
public long putIfAbsent( long key, long value ) {
int index = insertKey( key );
if (index < 0)
return _values[-index - 1];
return doPut( key, value, index );
}
private long doPut( long key, long value, int index ) {
long previous = no_entry_value;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public void putAll( Map<? extends Long, ? extends Long> map ) {
ensureCapacity( map.size() );
// could optimize this for cases when map instanceof THashMap
for ( Map.Entry<? extends Long, ? extends Long> entry : map.entrySet() ) {
this.put( entry.getKey().longValue(), entry.getValue().longValue() );
}
}
/** {@inheritDoc} */
public void putAll( TLongLongMap map ) {
ensureCapacity( map.size() );
TLongLongIterator iter = map.iterator();
while ( iter.hasNext() ) {
iter.advance();
this.put( iter.key(), iter.value() );
}
}
/** {@inheritDoc} */
public long get( long key ) {
int index = index( key );
return index < 0 ? no_entry_value : _values[index];
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, no_entry_key );
Arrays.fill( _values, 0, _values.length, no_entry_value );
Arrays.fill( _states, 0, _states.length, FREE );
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public long remove( long key ) {
long prev = no_entry_value;
int index = index( key );
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/** {@inheritDoc} */
protected void removeAt( int index ) {
_values[index] = no_entry_value;
super.removeAt( index ); // clear key, state; adjust size
}
/** {@inheritDoc} */
public TLongSet keySet() {
return new TKeyView();
}
/** {@inheritDoc} */
public long[] keys() {
long[] keys = new long[size()];
long[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
keys[j++] = k[i];
}
}
return keys;
}
/** {@inheritDoc} */
public long[] keys( long[] array ) {
int size = size();
if ( array.length < size ) {
array = new long[size];
}
long[] keys = _set;
byte[] states = _states;
for ( int i = keys.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = keys[i];
}
}
return array;
}
/** {@inheritDoc} */
public TLongCollection valueCollection() {
return new TValueView();
}
/** {@inheritDoc} */
public long[] values() {
long[] vals = new long[size()];
long[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
public long[] values( long[] array ) {
int size = size();
if ( array.length < size ) {
array = new long[size];
}
long[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = v[i];
}
}
return array;
}
/** {@inheritDoc} */
public boolean containsValue( long val ) {
byte[] states = _states;
long[] vals = _values;
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && val == vals[i] ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsKey( long key ) {
return contains( key );
}
/** {@inheritDoc} */
public TLongLongIterator iterator() {
return new TLongLongHashIterator( this );
}
/** {@inheritDoc} */
public boolean forEachKey( TLongProcedure procedure ) {
return forEach( procedure );
}
/** {@inheritDoc} */
public boolean forEachValue( TLongProcedure procedure ) {
byte[] states = _states;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean forEachEntry( TLongLongProcedure procedure ) {
byte[] states = _states;
long[] keys = _set;
long[] values = _values;
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public void transformValues( TLongFunction function ) {
byte[] states = _states;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
values[i] = function.execute( values[i] );
}
}
}
/** {@inheritDoc} */
public boolean retainEntries( TLongLongProcedure procedure ) {
boolean modified = false;
byte[] states = _states;
long[] keys = _set;
long[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
removeAt( i );
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/** {@inheritDoc} */
public boolean increment( long key ) {
return adjustValue( key, ( long ) 1 );
}
/** {@inheritDoc} */
public boolean adjustValue( long key, long amount ) {
int index = index( key );
if (index < 0) {
return false;
} else {
_values[index] += amount;
return true;
}
}
/** {@inheritDoc} */
public long adjustOrPutValue( long key, long adjust_amount, long put_amount ) {
int index = insertKey( key );
final boolean isNewMapping;
final long newValue;
if ( index < 0 ) {
index = -index -1;
newValue = ( _values[index] += adjust_amount );
isNewMapping = false;
} else {
newValue = ( _values[index] = put_amount );
isNewMapping = true;
}
byte previousState = _states[index];
if ( isNewMapping ) {
postInsertHook(consumeFreeSlot);
}
return newValue;
}
/** a view onto the keys of the map. */
protected class TKeyView implements TLongSet {
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongLongKeyHashIterator( TLongLongHashMap.this );
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_key;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( long entry ) {
return TLongLongHashMap.this.contains( entry );
}
/** {@inheritDoc} */
public long[] toArray() {
return TLongLongHashMap.this.keys();
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
return TLongLongHashMap.this.keys( dest );
}
/**
* Unsupported when operating upon a Key Set view of a TLongLongMap
* <p/>
* {@inheritDoc}
*/
public boolean add( long entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( long entry ) {
return no_entry_value != TLongLongHashMap.this.remove( entry );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long ele = ( ( Long ) element ).longValue();
if ( ! TLongLongHashMap.this.containsKey( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TLongLongHashMap.this.containsKey( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( long element : array ) {
if ( ! TLongLongHashMap.this.contains( element ) ) {
return false;
}
}
return true;
}
/**
* Unsupported when operating upon a Key Set view of a TLongLongMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( Collection<? extends Long> collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TLongLongMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( TLongCollection collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TLongLongMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( long[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TLongLongHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
return TLongLongHashMap.this.forEachKey( procedure );
}
@Override
public boolean equals( Object other ) {
if (! (other instanceof TLongSet)) {
return false;
}
final TLongSet that = ( TLongSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachKey( new TLongProcedure() {
private boolean first = true;
public boolean execute( long key ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( key );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
/** a view onto the values of the map. */
protected class TValueView implements TLongCollection {
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongLongValueHashIterator( TLongLongHashMap.this );
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( long entry ) {
return TLongLongHashMap.this.containsValue( entry );
}
/** {@inheritDoc} */
public long[] toArray() {
return TLongLongHashMap.this.values();
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
return TLongLongHashMap.this.values( dest );
}
public boolean add( long entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( long entry ) {
long[] values = _values;
long[] set = _set;
for ( int i = values.length; i-- > 0; ) {
if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) {
removeAt( i );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long ele = ( ( Long ) element ).longValue();
if ( ! TLongLongHashMap.this.containsValue( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TLongLongHashMap.this.containsValue( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( long element : array ) {
if ( ! TLongLongHashMap.this.containsValue( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Long> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TLongCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( long[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, values[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TLongLongHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
return TLongLongHashMap.this.forEachValue( procedure );
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachValue( new TLongProcedure() {
private boolean first = true;
public boolean execute( long value ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( value );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
class TLongLongKeyHashIterator extends THashPrimitiveIterator implements TLongIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TLongLongKeyHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _set[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TLongLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TLongLongValueHashIterator extends THashPrimitiveIterator implements TLongIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TLongLongValueHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _values[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TLongLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TLongLongHashIterator extends THashPrimitiveIterator implements TLongLongIterator {
/**
* Creates an iterator over the specified map
*
* @param map the <tt>TLongLongHashMap</tt> we will be iterating over.
*/
TLongLongHashIterator( TLongLongHashMap map ) {
super( map );
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
public long key() {
return _set[_index];
}
/** {@inheritDoc} */
public long value() {
return _values[_index];
}
/** {@inheritDoc} */
public long setValue( long val ) {
long old = value();
_values[_index] = val;
return old;
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TLongLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
/** {@inheritDoc} */
@Override
public boolean equals( Object other ) {
if ( ! ( other instanceof TLongLongMap ) ) {
return false;
}
TLongLongMap that = ( TLongLongMap ) other;
if ( that.size() != this.size() ) {
return false;
}
long[] values = _values;
byte[] states = _states;
long this_no_entry_value = getNoEntryValue();
long that_no_entry_value = that.getNoEntryValue();
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
long key = _set[i];
long that_value = that.get( key );
long this_value = values[i];
if ( ( this_value != that_value ) &&
( this_value != this_no_entry_value ) &&
( that_value != that_no_entry_value ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int hashcode = 0;
byte[] states = _states;
for ( int i = _values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] ) ^
HashFunctions.hash( _values[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachEntry( new TLongLongProcedure() {
private boolean first = true;
public boolean execute( long key, long value ) {
if ( first ) first = false;
else buf.append( ", " );
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append( "}" );
return buf.toString();
}
/** {@inheritDoc} */
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeLong( _set[i] );
out.writeLong( _values[i] );
}
}
}
/** {@inheritDoc} */
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
long key = in.readLong();
long val = in.readLong();
put(key, val);
}
}
} // TLongLongHashMap
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
import gnu.trove.map.TLongObjectMap;
import gnu.trove.impl.Constants;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.hash.*;
import gnu.trove.procedure.TLongObjectProcedure;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.iterator.TLongIterator;
import gnu.trove.iterator.TLongObjectIterator;
import gnu.trove.iterator.TPrimitiveIterator;
import gnu.trove.function.TObjectFunction;
import gnu.trove.set.TLongSet;
import gnu.trove.TLongCollection;
import java.io.*;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed Map implementation for long keys and Object values.
*
* Created: Sun Nov 4 08:52:45 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
*/
public class TLongObjectHashMap<V> extends TLongHash implements
TLongObjectMap<V>, Externalizable {
static final long serialVersionUID = 1L;
private final TLongObjectProcedure<V> PUT_ALL_PROC = new TLongObjectProcedure<V>() {
public boolean execute( long key, V value) {
put( key, value );
return true;
}
};
/** the values of the map */
protected transient V[] _values;
/** the value that represents null in the key set. */
protected long no_entry_key;
/**
* Creates a new <code>TLongObjectHashMap</code> instance with the default
* capacity and load factor.
*/
public TLongObjectHashMap() {
super();
}
/**
* Creates a new <code>TLongObjectHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongObjectHashMap( int initialCapacity ) {
super( initialCapacity );
no_entry_key = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TLongObjectHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TLongObjectHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
no_entry_key = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TLongObjectHashMap</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param noEntryKey the value used to represent null in the key set.
*/
public TLongObjectHashMap( int initialCapacity, float loadFactor, long noEntryKey ) {
super( initialCapacity, loadFactor );
no_entry_key = noEntryKey;
}
/**
* Creates a new <code>TLongObjectHashMap</code> that contains the entries
* in the map passed to it.
*
* @param map the <tt>TLongObjectMap</tt> to be copied.
*/
public TLongObjectHashMap( TLongObjectMap<? extends V> map ) {
this( map.size(), 0.5f, map.getNoEntryKey() );
putAll( map );
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = ( V[] ) new Object[capacity];
return capacity;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
long oldKeys[] = _set;
V oldVals[] = _values;
byte oldStates[] = _states;
_set = new long[newCapacity];
_values = (V[]) new Object[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
long o = oldKeys[i];
int index = insertKey(o);
_values[index] = oldVals[i];
}
}
}
// Query Operations
/** {@inheritDoc} */
public long getNoEntryKey() {
return no_entry_key;
}
/** {@inheritDoc} */
public boolean containsKey( long key ) {
return contains( key );
}
/** {@inheritDoc} */
public boolean containsValue( Object val ) {
byte[] states = _states;
V[] vals = _values;
// special case null values so that we don't have to
// perform null checks before every call to equals()
if ( null == val ) {
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && null == vals[i] ) {
return true;
}
}
} else {
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL &&
( val == vals[i] || val.equals( vals[i] ) ) ) {
return true;
}
}
} // end of else
return false;
}
/** {@inheritDoc} */
public V get( long key ) {
int index = index( key );
return index < 0 ? null : _values[index];
}
// Modification Operations
/** {@inheritDoc} */
public V put( long key, V value ) {
int index = insertKey( key );
return doPut( value, index );
}
/** {@inheritDoc} */
public V putIfAbsent( long key, V value ) {
int index = insertKey( key );
if ( index < 0 )
return _values[-index - 1];
return doPut( value, index );
}
@SuppressWarnings({"unchecked"})
private V doPut( V value, int index ) {
V previous = null;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public V remove( long key ) {
V prev = null;
int index = index( key );
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/** {@inheritDoc} */
protected void removeAt( int index ) {
_values[index] = null;
super.removeAt( index ); // clear key, state; adjust size
}
// Bulk Operations
/** {@inheritDoc} */
public void putAll( Map<? extends Long, ? extends V> map ) {
Set<? extends Map.Entry<? extends Long,? extends V>> set = map.entrySet();
for ( Map.Entry<? extends Long,? extends V> entry : set ) {
put( entry.getKey(), entry.getValue() );
}
}
/** {@inheritDoc} */
public void putAll( TLongObjectMap<? extends V> map ){
map.forEachEntry( PUT_ALL_PROC );
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, no_entry_key );
Arrays.fill( _states, 0, _states.length, FREE );
Arrays.fill( _values, 0, _values.length, null );
}
// Views
/** {@inheritDoc} */
public TLongSet keySet() {
return new KeyView();
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public long[] keys() {
long[] keys = new long[size()];
long[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
keys[j++] = k[i];
}
}
return keys;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public long[] keys( long[] dest ) {
if ( dest.length < _size ) {
dest = new long[_size];
}
long[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
dest[j++] = k[i];
}
}
return dest;
}
/** {@inheritDoc} */
public Collection<V> valueCollection() {
return new ValueView();
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public V[] values() {
V[] vals = ( V[] ) new Object[size()];
V[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public V[] values( V[] dest ) {
if ( dest.length < _size ) {
dest = ( V[] ) java.lang.reflect.Array.newInstance(
dest.getClass().getComponentType(), _size);
}
V[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
dest[j++] = ( V ) v[i];
}
}
return dest;
}
/** {@inheritDoc} */
public TLongObjectIterator<V> iterator() {
return new TLongObjectHashIterator<V>( this );
}
/** {@inheritDoc} */
public boolean forEachKey( TLongProcedure procedure ) {
return forEach( procedure );
}
/** {@inheritDoc} */
public boolean forEachValue( TObjectProcedure<? super V> procedure ) {
byte[] states = _states;
V[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public boolean forEachEntry( TLongObjectProcedure<? super V> procedure ) {
byte[] states = _states;
long[] keys = _set;
V[] values = _values;
for (int i = keys.length; i-- > 0;) {
if (states[i] == FULL && ! procedure.execute(keys[i],values[i])) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public boolean retainEntries( TLongObjectProcedure<? super V> procedure ) {
boolean modified = false;
byte[] states = _states;
long[] keys = _set;
V[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
removeAt( i );
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/** {@inheritDoc} */
public void transformValues( TObjectFunction<V,V> function ) {
byte[] states = _states;
V[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
values[i] = function.execute( values[i] );
}
}
}
// Comparison and hashing
/** {@inheritDoc} */
public boolean equals( Object other ) {
if ( ! ( other instanceof TLongObjectMap ) ) {
return false;
}
TLongObjectMap that = ( TLongObjectMap ) other;
if ( that.size() != this.size() ) {
return false;
}
try {
TLongObjectIterator iter = this.iterator();
while ( iter.hasNext() ) {
iter.advance();
long key = iter.key();
Object value = iter.value();
if ( value == null ) {
if ( !( that.get( key ) == null && that.containsKey( key ) ) ) {
return false;
}
} else {
if ( !value.equals( that.get( key ) ) ) {
return false;
}
}
}
} catch ( ClassCastException ex ) {
// unused.
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
V[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] ) ^
( values[i] == null ? 0 : values[i].hashCode() );
}
}
return hashcode;
}
class KeyView implements TLongSet {
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_key;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return _size == 0;
}
/** {@inheritDoc} */
public boolean contains( long entry ) {
return TLongObjectHashMap.this.containsKey( entry );
}
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongHashIterator( TLongObjectHashMap.this );
}
/** {@inheritDoc} */
public long[] toArray() {
return keys();
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
return keys( dest );
}
/** {@inheritDoc} */
public boolean add( long entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( long entry ) {
return null != TLongObjectHashMap.this.remove( entry );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( ! TLongObjectHashMap.this.containsKey(
( ( Long ) element ).longValue() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
if ( collection == this ) {
return true;
}
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TLongObjectHashMap.this.containsKey( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( long element : array ) {
if ( ! TLongObjectHashMap.this.containsKey( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Long> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TLongCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( long[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
//noinspection SuspiciousMethodCalls
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( collection == this ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove(array[i]) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TLongObjectHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
return TLongObjectHashMap.this.forEachKey( procedure );
}
/** {@inheritDoc) */
public boolean equals( Object other ) {
if (! ( other instanceof TLongSet ) ) {
return false;
}
final TLongSet that = ( TLongSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
public String toString() {
final StringBuilder buf = new StringBuilder("{");
boolean first = true;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( first ) first = false;
else buf.append( "," );
buf.append( _set[i] );
}
}
return buf.toString();
}
class TLongHashIterator extends THashPrimitiveIterator implements TLongIterator {
/** the collection on which the iterator operates */
private final TLongHash _hash;
/** {@inheritDoc} */
public TLongHashIterator( TLongHash hash ) {
super( hash );
this._hash = hash;
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _hash._set[_index];
}
}
}
/** a view onto the values of the map. */
protected class ValueView extends MapBackedView<V> {
@SuppressWarnings({"unchecked"})
public Iterator<V> iterator() {
return new TLongObjectValueHashIterator( TLongObjectHashMap.this ) {
protected V objectAtIndex( int index ) {
return _values[index];
}
};
}
public boolean containsElement( V value ) {
return containsValue( value );
}
public boolean removeElement( V value ) {
V[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
if ( value == values[i] ||
( null != values[i] && values[i].equals( value ) ) ) {
removeAt( i );
return true;
}
}
}
return false;
}
class TLongObjectValueHashIterator extends THashPrimitiveIterator
implements Iterator<V> {
protected final TLongObjectHashMap _map;
public TLongObjectValueHashIterator( TLongObjectHashMap map ) {
super( map );
_map = map;
}
@SuppressWarnings("unchecked")
protected V objectAtIndex( int index ) {
byte[] states = _states;
Object value = _map._values[index];
if ( states[index] != FULL ) {
return null;
}
return ( V ) value;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
public V next() {
moveToNextIndex();
return ( V ) _map._values[_index];
}
}
}
private abstract class MapBackedView<E> extends AbstractSet<E>
implements Set<E>, Iterable<E> {
public abstract Iterator<E> iterator();
public abstract boolean removeElement( E key );
public abstract boolean containsElement( E key );
@SuppressWarnings({"unchecked"})
public boolean contains( Object key ) {
return containsElement( (E) key );
}
@SuppressWarnings({"unchecked"})
public boolean remove( Object o ) {
return removeElement( (E) o );
}
public void clear() {
TLongObjectHashMap.this.clear();
}
public boolean add( E obj ) {
throw new UnsupportedOperationException();
}
public int size() {
return TLongObjectHashMap.this.size();
}
public Object[] toArray() {
Object[] result = new Object[size()];
Iterator<E> e = iterator();
for ( int i = 0; e.hasNext(); i++ ) {
result[i] = e.next();
}
return result;
}
@SuppressWarnings({"unchecked"})
public <T> T[] toArray( T[] a ) {
int size = size();
if ( a.length < size ) {
a = (T[]) java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size );
}
Iterator<E> it = iterator();
Object[] result = a;
for ( int i = 0; i < size; i++ ) {
result[i] = it.next();
}
if ( a.length > size ) {
a[size] = null;
}
return a;
}
public boolean isEmpty() {
return TLongObjectHashMap.this.isEmpty();
}
public boolean addAll( Collection<? extends E> collection ) {
throw new UnsupportedOperationException();
}
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean changed = false;
Iterator<E> i = iterator();
while ( i.hasNext() ) {
if ( !collection.contains( i.next() ) ) {
i.remove();
changed = true;
}
}
return changed;
}
}
class TLongObjectHashIterator<V> extends THashPrimitiveIterator
implements TLongObjectIterator<V> {
/** the collection being iterated over */
private final TLongObjectHashMap<V> _map;
/**
* Creates an iterator over the specified map
*
* @param map map to iterate over.
*/
public TLongObjectHashIterator( TLongObjectHashMap<V> map ) {
super( map );
this._map = map;
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
public long key() {
return _map._set[_index];
}
/** {@inheritDoc} */
public V value() {
return _map._values[_index];
}
/** {@inheritDoc} */
public V setValue( V val ) {
V old = value();
_map._values[_index] = val;
return old;
}
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeLong( no_entry_key );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeLong( _set[i] );
out.writeObject( _values[i] );
}
}
}
@SuppressWarnings({"unchecked"})
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readLong();
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
long key = in.readLong();
V val = (V) in.readObject();
put(key, val);
}
}
public String toString() {
final StringBuilder buf = new StringBuilder("{");
forEachEntry(new TLongObjectProcedure<V>() {
private boolean first = true;
public boolean execute(long key, Object value) {
if ( first ) first = false;
else buf.append( "," );
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append("}");
return buf.toString();
}
} // TLongObjectHashMap
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.map.TLongIntMap;
import gnu.trove.function.TIntFunction;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.iterator.*;
import gnu.trove.iterator.hash.*;
import gnu.trove.impl.hash.*;
import gnu.trove.impl.HashFunctions;
import gnu.trove.*;
import java.io.*;
import java.util.*;
/**
* An open addressed Map implementation for long keys and int values.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_HashMap.template,v 1.1.2.16 2010/03/02 04:09:50 robeden Exp $
*/
public class TLongIntHashMap extends TLongIntHash implements TLongIntMap, Externalizable {
static final long serialVersionUID = 1L;
/** the values of the map */
protected transient int[] _values;
/**
* Creates a new <code>TLongIntHashMap</code> instance with the default
* capacity and load factor.
*/
public TLongIntHashMap() {
super();
}
/**
* Creates a new <code>TLongIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongIntHashMap( int initialCapacity ) {
super( initialCapacity );
}
/**
* Creates a new <code>TLongIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TLongIntHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
}
/**
* Creates a new <code>TLongIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
* @param noEntryKey a <code>long</code> value that represents
* <tt>null</tt> for the Key set.
* @param noEntryValue a <code>int</code> value that represents
* <tt>null</tt> for the Value set.
*/
public TLongIntHashMap( int initialCapacity, float loadFactor,
long noEntryKey, int noEntryValue ) {
super( initialCapacity, loadFactor, noEntryKey, noEntryValue );
}
/**
* Creates a new <code>TLongIntHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param keys a <tt>long</tt> array containing the keys for the matching values.
* @param values a <tt>int</tt> array containing the values.
*/
public TLongIntHashMap( long[] keys, int[] values ) {
super( Math.max( keys.length, values.length ) );
int size = Math.min( keys.length, values.length );
for ( int i = 0; i < size; i++ ) {
this.put( keys[i], values[i] );
}
}
/**
* Creates a new <code>TLongIntHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param map a <tt>TLongIntMap</tt> that will be duplicated.
*/
public TLongIntHashMap( TLongIntMap map ) {
super( map.size() );
if ( map instanceof TLongIntHashMap ) {
TLongIntHashMap hashmap = ( TLongIntHashMap ) map;
this._loadFactor = hashmap._loadFactor;
this.no_entry_key = hashmap.no_entry_key;
this.no_entry_value = hashmap.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_key != ( long ) 0 ) {
Arrays.fill( _set, this.no_entry_key );
}
//noinspection RedundantCast
if ( this.no_entry_value != ( int ) 0 ) {
Arrays.fill( _values, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
putAll( map );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = new int[capacity];
return capacity;
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
/** {@inheritDoc} */
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
long oldKeys[] = _set;
int oldVals[] = _values;
byte oldStates[] = _states;
_set = new long[newCapacity];
_values = new int[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
long o = oldKeys[i];
int index = insertKey( o );
_values[index] = oldVals[i];
}
}
}
/** {@inheritDoc} */
public int put( long key, int value ) {
int index = insertKey( key );
return doPut( key, value, index );
}
/** {@inheritDoc} */
public int putIfAbsent( long key, int value ) {
int index = insertKey( key );
if (index < 0)
return _values[-index - 1];
return doPut( key, value, index );
}
private int doPut( long key, int value, int index ) {
int previous = no_entry_value;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public void putAll( Map<? extends Long, ? extends Integer> map ) {
ensureCapacity( map.size() );
// could optimize this for cases when map instanceof THashMap
for ( Map.Entry<? extends Long, ? extends Integer> entry : map.entrySet() ) {
this.put( entry.getKey().longValue(), entry.getValue().intValue() );
}
}
/** {@inheritDoc} */
public void putAll( TLongIntMap map ) {
ensureCapacity( map.size() );
TLongIntIterator iter = map.iterator();
while ( iter.hasNext() ) {
iter.advance();
this.put( iter.key(), iter.value() );
}
}
/** {@inheritDoc} */
public int get( long key ) {
int index = index( key );
return index < 0 ? no_entry_value : _values[index];
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, no_entry_key );
Arrays.fill( _values, 0, _values.length, no_entry_value );
Arrays.fill( _states, 0, _states.length, FREE );
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public int remove( long key ) {
int prev = no_entry_value;
int index = index( key );
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/** {@inheritDoc} */
protected void removeAt( int index ) {
_values[index] = no_entry_value;
super.removeAt( index ); // clear key, state; adjust size
}
/** {@inheritDoc} */
public TLongSet keySet() {
return new TKeyView();
}
/** {@inheritDoc} */
public long[] keys() {
long[] keys = new long[size()];
long[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
keys[j++] = k[i];
}
}
return keys;
}
/** {@inheritDoc} */
public long[] keys( long[] array ) {
int size = size();
if ( array.length < size ) {
array = new long[size];
}
long[] keys = _set;
byte[] states = _states;
for ( int i = keys.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = keys[i];
}
}
return array;
}
/** {@inheritDoc} */
public TIntCollection valueCollection() {
return new TValueView();
}
/** {@inheritDoc} */
public int[] values() {
int[] vals = new int[size()];
int[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
public int[] values( int[] array ) {
int size = size();
if ( array.length < size ) {
array = new int[size];
}
int[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = v[i];
}
}
return array;
}
/** {@inheritDoc} */
public boolean containsValue( int val ) {
byte[] states = _states;
int[] vals = _values;
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && val == vals[i] ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsKey( long key ) {
return contains( key );
}
/** {@inheritDoc} */
public TLongIntIterator iterator() {
return new TLongIntHashIterator( this );
}
/** {@inheritDoc} */
public boolean forEachKey( TLongProcedure procedure ) {
return forEach( procedure );
}
/** {@inheritDoc} */
public boolean forEachValue( TIntProcedure procedure ) {
byte[] states = _states;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean forEachEntry( TLongIntProcedure procedure ) {
byte[] states = _states;
long[] keys = _set;
int[] values = _values;
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public void transformValues( TIntFunction function ) {
byte[] states = _states;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
values[i] = function.execute( values[i] );
}
}
}
/** {@inheritDoc} */
public boolean retainEntries( TLongIntProcedure procedure ) {
boolean modified = false;
byte[] states = _states;
long[] keys = _set;
int[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
removeAt( i );
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/** {@inheritDoc} */
public boolean increment( long key ) {
return adjustValue( key, ( int ) 1 );
}
/** {@inheritDoc} */
public boolean adjustValue( long key, int amount ) {
int index = index( key );
if (index < 0) {
return false;
} else {
_values[index] += amount;
return true;
}
}
/** {@inheritDoc} */
public int adjustOrPutValue( long key, int adjust_amount, int put_amount ) {
int index = insertKey( key );
final boolean isNewMapping;
final int newValue;
if ( index < 0 ) {
index = -index -1;
newValue = ( _values[index] += adjust_amount );
isNewMapping = false;
} else {
newValue = ( _values[index] = put_amount );
isNewMapping = true;
}
byte previousState = _states[index];
if ( isNewMapping ) {
postInsertHook(consumeFreeSlot);
}
return newValue;
}
/** a view onto the keys of the map. */
protected class TKeyView implements TLongSet {
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongIntKeyHashIterator( TLongIntHashMap.this );
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_key;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( long entry ) {
return TLongIntHashMap.this.contains( entry );
}
/** {@inheritDoc} */
public long[] toArray() {
return TLongIntHashMap.this.keys();
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
return TLongIntHashMap.this.keys( dest );
}
/**
* Unsupported when operating upon a Key Set view of a TLongIntMap
* <p/>
* {@inheritDoc}
*/
public boolean add( long entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( long entry ) {
return no_entry_value != TLongIntHashMap.this.remove( entry );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long ele = ( ( Long ) element ).longValue();
if ( ! TLongIntHashMap.this.containsKey( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TLongIntHashMap.this.containsKey( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( long element : array ) {
if ( ! TLongIntHashMap.this.contains( element ) ) {
return false;
}
}
return true;
}
/**
* Unsupported when operating upon a Key Set view of a TLongIntMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( Collection<? extends Long> collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TLongIntMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( TLongCollection collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TLongIntMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( long[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TLongIntHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
return TLongIntHashMap.this.forEachKey( procedure );
}
@Override
public boolean equals( Object other ) {
if (! (other instanceof TLongSet)) {
return false;
}
final TLongSet that = ( TLongSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachKey( new TLongProcedure() {
private boolean first = true;
public boolean execute( long key ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( key );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
/** a view onto the values of the map. */
protected class TValueView implements TIntCollection {
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TLongIntValueHashIterator( TLongIntHashMap.this );
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( int entry ) {
return TLongIntHashMap.this.containsValue( entry );
}
/** {@inheritDoc} */
public int[] toArray() {
return TLongIntHashMap.this.values();
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
return TLongIntHashMap.this.values( dest );
}
public boolean add( int entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( int entry ) {
int[] values = _values;
long[] set = _set;
for ( int i = values.length; i-- > 0; ) {
if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) {
removeAt( i );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int ele = ( ( Integer ) element ).intValue();
if ( ! TLongIntHashMap.this.containsValue( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TLongIntHashMap.this.containsValue( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int element : array ) {
if ( ! TLongIntHashMap.this.containsValue( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Integer> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TIntCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( int[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, values[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TLongIntHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
return TLongIntHashMap.this.forEachValue( procedure );
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachValue( new TIntProcedure() {
private boolean first = true;
public boolean execute( int value ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( value );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
class TLongIntKeyHashIterator extends THashPrimitiveIterator implements TLongIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TLongIntKeyHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _set[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TLongIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TLongIntValueHashIterator extends THashPrimitiveIterator implements TIntIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TLongIntValueHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _values[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TLongIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TLongIntHashIterator extends THashPrimitiveIterator implements TLongIntIterator {
/**
* Creates an iterator over the specified map
*
* @param map the <tt>TLongIntHashMap</tt> we will be iterating over.
*/
TLongIntHashIterator( TLongIntHashMap map ) {
super( map );
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
public long key() {
return _set[_index];
}
/** {@inheritDoc} */
public int value() {
return _values[_index];
}
/** {@inheritDoc} */
public int setValue( int val ) {
int old = value();
_values[_index] = val;
return old;
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TLongIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
/** {@inheritDoc} */
@Override
public boolean equals( Object other ) {
if ( ! ( other instanceof TLongIntMap ) ) {
return false;
}
TLongIntMap that = ( TLongIntMap ) other;
if ( that.size() != this.size() ) {
return false;
}
int[] values = _values;
byte[] states = _states;
int this_no_entry_value = getNoEntryValue();
int that_no_entry_value = that.getNoEntryValue();
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
long key = _set[i];
int that_value = that.get( key );
int this_value = values[i];
if ( ( this_value != that_value ) &&
( this_value != this_no_entry_value ) &&
( that_value != that_no_entry_value ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int hashcode = 0;
byte[] states = _states;
for ( int i = _values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] ) ^
HashFunctions.hash( _values[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachEntry( new TLongIntProcedure() {
private boolean first = true;
public boolean execute( long key, int value ) {
if ( first ) first = false;
else buf.append( ", " );
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append( "}" );
return buf.toString();
}
/** {@inheritDoc} */
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeLong( _set[i] );
out.writeInt( _values[i] );
}
}
}
/** {@inheritDoc} */
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
long key = in.readLong();
int val = in.readInt();
put(key, val);
}
}
} // TLongIntHashMap
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.impl.Constants;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.hash.*;
import gnu.trove.procedure.TIntObjectProcedure;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.iterator.TIntObjectIterator;
import gnu.trove.iterator.TPrimitiveIterator;
import gnu.trove.function.TObjectFunction;
import gnu.trove.set.TIntSet;
import gnu.trove.TIntCollection;
import java.io.*;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed Map implementation for int keys and Object values.
*
* Created: Sun Nov 4 08:52:45 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
*/
public class TIntObjectHashMap<V> extends TIntHash implements
TIntObjectMap<V>, Externalizable {
static final long serialVersionUID = 1L;
private final TIntObjectProcedure<V> PUT_ALL_PROC = new TIntObjectProcedure<V>() {
public boolean execute( int key, V value) {
put( key, value );
return true;
}
};
/** the values of the map */
protected transient V[] _values;
/** the value that represents null in the key set. */
protected int no_entry_key;
/**
* Creates a new <code>TIntObjectHashMap</code> instance with the default
* capacity and load factor.
*/
public TIntObjectHashMap() {
super();
}
/**
* Creates a new <code>TIntObjectHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntObjectHashMap( int initialCapacity ) {
super( initialCapacity );
no_entry_key = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TIntObjectHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TIntObjectHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
no_entry_key = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TIntObjectHashMap</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param noEntryKey the value used to represent null in the key set.
*/
public TIntObjectHashMap( int initialCapacity, float loadFactor, int noEntryKey ) {
super( initialCapacity, loadFactor );
no_entry_key = noEntryKey;
}
/**
* Creates a new <code>TIntObjectHashMap</code> that contains the entries
* in the map passed to it.
*
* @param map the <tt>TIntObjectMap</tt> to be copied.
*/
public TIntObjectHashMap( TIntObjectMap<? extends V> map ) {
this( map.size(), 0.5f, map.getNoEntryKey() );
putAll( map );
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = ( V[] ) new Object[capacity];
return capacity;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
int oldKeys[] = _set;
V oldVals[] = _values;
byte oldStates[] = _states;
_set = new int[newCapacity];
_values = (V[]) new Object[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
int o = oldKeys[i];
int index = insertKey(o);
_values[index] = oldVals[i];
}
}
}
// Query Operations
/** {@inheritDoc} */
public int getNoEntryKey() {
return no_entry_key;
}
/** {@inheritDoc} */
public boolean containsKey( int key ) {
return contains( key );
}
/** {@inheritDoc} */
public boolean containsValue( Object val ) {
byte[] states = _states;
V[] vals = _values;
// special case null values so that we don't have to
// perform null checks before every call to equals()
if ( null == val ) {
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && null == vals[i] ) {
return true;
}
}
} else {
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL &&
( val == vals[i] || val.equals( vals[i] ) ) ) {
return true;
}
}
} // end of else
return false;
}
/** {@inheritDoc} */
public V get( int key ) {
int index = index( key );
return index < 0 ? null : _values[index];
}
// Modification Operations
/** {@inheritDoc} */
public V put( int key, V value ) {
int index = insertKey( key );
return doPut( value, index );
}
/** {@inheritDoc} */
public V putIfAbsent( int key, V value ) {
int index = insertKey( key );
if ( index < 0 )
return _values[-index - 1];
return doPut( value, index );
}
@SuppressWarnings({"unchecked"})
private V doPut( V value, int index ) {
V previous = null;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public V remove( int key ) {
V prev = null;
int index = index( key );
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/** {@inheritDoc} */
protected void removeAt( int index ) {
_values[index] = null;
super.removeAt( index ); // clear key, state; adjust size
}
// Bulk Operations
/** {@inheritDoc} */
public void putAll( Map<? extends Integer, ? extends V> map ) {
Set<? extends Map.Entry<? extends Integer,? extends V>> set = map.entrySet();
for ( Map.Entry<? extends Integer,? extends V> entry : set ) {
put( entry.getKey(), entry.getValue() );
}
}
/** {@inheritDoc} */
public void putAll( TIntObjectMap<? extends V> map ){
map.forEachEntry( PUT_ALL_PROC );
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, no_entry_key );
Arrays.fill( _states, 0, _states.length, FREE );
Arrays.fill( _values, 0, _values.length, null );
}
// Views
/** {@inheritDoc} */
public TIntSet keySet() {
return new KeyView();
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public int[] keys() {
int[] keys = new int[size()];
int[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
keys[j++] = k[i];
}
}
return keys;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public int[] keys( int[] dest ) {
if ( dest.length < _size ) {
dest = new int[_size];
}
int[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
dest[j++] = k[i];
}
}
return dest;
}
/** {@inheritDoc} */
public Collection<V> valueCollection() {
return new ValueView();
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public V[] values() {
V[] vals = ( V[] ) new Object[size()];
V[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public V[] values( V[] dest ) {
if ( dest.length < _size ) {
dest = ( V[] ) java.lang.reflect.Array.newInstance(
dest.getClass().getComponentType(), _size);
}
V[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
dest[j++] = ( V ) v[i];
}
}
return dest;
}
/** {@inheritDoc} */
public TIntObjectIterator<V> iterator() {
return new TIntObjectHashIterator<V>( this );
}
/** {@inheritDoc} */
public boolean forEachKey( TIntProcedure procedure ) {
return forEach( procedure );
}
/** {@inheritDoc} */
public boolean forEachValue( TObjectProcedure<? super V> procedure ) {
byte[] states = _states;
V[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public boolean forEachEntry( TIntObjectProcedure<? super V> procedure ) {
byte[] states = _states;
int[] keys = _set;
V[] values = _values;
for (int i = keys.length; i-- > 0;) {
if (states[i] == FULL && ! procedure.execute(keys[i],values[i])) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public boolean retainEntries( TIntObjectProcedure<? super V> procedure ) {
boolean modified = false;
byte[] states = _states;
int[] keys = _set;
V[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
removeAt( i );
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/** {@inheritDoc} */
public void transformValues( TObjectFunction<V,V> function ) {
byte[] states = _states;
V[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
values[i] = function.execute( values[i] );
}
}
}
// Comparison and hashing
/** {@inheritDoc} */
public boolean equals( Object other ) {
if ( ! ( other instanceof TIntObjectMap ) ) {
return false;
}
TIntObjectMap that = ( TIntObjectMap ) other;
if ( that.size() != this.size() ) {
return false;
}
try {
TIntObjectIterator iter = this.iterator();
while ( iter.hasNext() ) {
iter.advance();
int key = iter.key();
Object value = iter.value();
if ( value == null ) {
if ( !( that.get( key ) == null && that.containsKey( key ) ) ) {
return false;
}
} else {
if ( !value.equals( that.get( key ) ) ) {
return false;
}
}
}
} catch ( ClassCastException ex ) {
// unused.
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
V[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] ) ^
( values[i] == null ? 0 : values[i].hashCode() );
}
}
return hashcode;
}
class KeyView implements TIntSet {
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_key;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return _size == 0;
}
/** {@inheritDoc} */
public boolean contains( int entry ) {
return TIntObjectHashMap.this.containsKey( entry );
}
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntHashIterator( TIntObjectHashMap.this );
}
/** {@inheritDoc} */
public int[] toArray() {
return keys();
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
return keys( dest );
}
/** {@inheritDoc} */
public boolean add( int entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( int entry ) {
return null != TIntObjectHashMap.this.remove( entry );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( ! TIntObjectHashMap.this.containsKey(
( ( Integer ) element ).intValue() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
if ( collection == this ) {
return true;
}
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TIntObjectHashMap.this.containsKey( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int element : array ) {
if ( ! TIntObjectHashMap.this.containsKey( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Integer> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TIntCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( int[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
//noinspection SuspiciousMethodCalls
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( collection == this ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove(array[i]) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TIntObjectHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
return TIntObjectHashMap.this.forEachKey( procedure );
}
/** {@inheritDoc) */
public boolean equals( Object other ) {
if (! ( other instanceof TIntSet ) ) {
return false;
}
final TIntSet that = ( TIntSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
public String toString() {
final StringBuilder buf = new StringBuilder("{");
boolean first = true;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( first ) first = false;
else buf.append( "," );
buf.append( _set[i] );
}
}
return buf.toString();
}
class TIntHashIterator extends THashPrimitiveIterator implements TIntIterator {
/** the collection on which the iterator operates */
private final TIntHash _hash;
/** {@inheritDoc} */
public TIntHashIterator( TIntHash hash ) {
super( hash );
this._hash = hash;
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _hash._set[_index];
}
}
}
/** a view onto the values of the map. */
protected class ValueView extends MapBackedView<V> {
@SuppressWarnings({"unchecked"})
public Iterator<V> iterator() {
return new TIntObjectValueHashIterator( TIntObjectHashMap.this ) {
protected V objectAtIndex( int index ) {
return _values[index];
}
};
}
public boolean containsElement( V value ) {
return containsValue( value );
}
public boolean removeElement( V value ) {
V[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
if ( value == values[i] ||
( null != values[i] && values[i].equals( value ) ) ) {
removeAt( i );
return true;
}
}
}
return false;
}
class TIntObjectValueHashIterator extends THashPrimitiveIterator
implements Iterator<V> {
protected final TIntObjectHashMap _map;
public TIntObjectValueHashIterator( TIntObjectHashMap map ) {
super( map );
_map = map;
}
@SuppressWarnings("unchecked")
protected V objectAtIndex( int index ) {
byte[] states = _states;
Object value = _map._values[index];
if ( states[index] != FULL ) {
return null;
}
return ( V ) value;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
public V next() {
moveToNextIndex();
return ( V ) _map._values[_index];
}
}
}
private abstract class MapBackedView<E> extends AbstractSet<E>
implements Set<E>, Iterable<E> {
public abstract Iterator<E> iterator();
public abstract boolean removeElement( E key );
public abstract boolean containsElement( E key );
@SuppressWarnings({"unchecked"})
public boolean contains( Object key ) {
return containsElement( (E) key );
}
@SuppressWarnings({"unchecked"})
public boolean remove( Object o ) {
return removeElement( (E) o );
}
public void clear() {
TIntObjectHashMap.this.clear();
}
public boolean add( E obj ) {
throw new UnsupportedOperationException();
}
public int size() {
return TIntObjectHashMap.this.size();
}
public Object[] toArray() {
Object[] result = new Object[size()];
Iterator<E> e = iterator();
for ( int i = 0; e.hasNext(); i++ ) {
result[i] = e.next();
}
return result;
}
@SuppressWarnings({"unchecked"})
public <T> T[] toArray( T[] a ) {
int size = size();
if ( a.length < size ) {
a = (T[]) java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size );
}
Iterator<E> it = iterator();
Object[] result = a;
for ( int i = 0; i < size; i++ ) {
result[i] = it.next();
}
if ( a.length > size ) {
a[size] = null;
}
return a;
}
public boolean isEmpty() {
return TIntObjectHashMap.this.isEmpty();
}
public boolean addAll( Collection<? extends E> collection ) {
throw new UnsupportedOperationException();
}
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean changed = false;
Iterator<E> i = iterator();
while ( i.hasNext() ) {
if ( !collection.contains( i.next() ) ) {
i.remove();
changed = true;
}
}
return changed;
}
}
class TIntObjectHashIterator<V> extends THashPrimitiveIterator
implements TIntObjectIterator<V> {
/** the collection being iterated over */
private final TIntObjectHashMap<V> _map;
/**
* Creates an iterator over the specified map
*
* @param map map to iterate over.
*/
public TIntObjectHashIterator( TIntObjectHashMap<V> map ) {
super( map );
this._map = map;
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
public int key() {
return _map._set[_index];
}
/** {@inheritDoc} */
public V value() {
return _map._values[_index];
}
/** {@inheritDoc} */
public V setValue( V val ) {
V old = value();
_map._values[_index] = val;
return old;
}
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeInt( no_entry_key );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeInt( _set[i] );
out.writeObject( _values[i] );
}
}
}
@SuppressWarnings({"unchecked"})
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readInt();
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
int key = in.readInt();
V val = (V) in.readObject();
put(key, val);
}
}
public String toString() {
final StringBuilder buf = new StringBuilder("{");
forEachEntry(new TIntObjectProcedure<V>() {
private boolean first = true;
public boolean execute(int key, Object value) {
if ( first ) first = false;
else buf.append( "," );
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append("}");
return buf.toString();
}
} // TIntObjectHashMap
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.map.TIntLongMap;
import gnu.trove.function.TLongFunction;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.iterator.*;
import gnu.trove.iterator.hash.*;
import gnu.trove.impl.hash.*;
import gnu.trove.impl.HashFunctions;
import gnu.trove.*;
import java.io.*;
import java.util.*;
/**
* An open addressed Map implementation for int keys and long values.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_HashMap.template,v 1.1.2.16 2010/03/02 04:09:50 robeden Exp $
*/
public class TIntLongHashMap extends TIntLongHash implements TIntLongMap, Externalizable {
static final long serialVersionUID = 1L;
/** the values of the map */
protected transient long[] _values;
/**
* Creates a new <code>TIntLongHashMap</code> instance with the default
* capacity and load factor.
*/
public TIntLongHashMap() {
super();
}
/**
* Creates a new <code>TIntLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntLongHashMap( int initialCapacity ) {
super( initialCapacity );
}
/**
* Creates a new <code>TIntLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TIntLongHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
}
/**
* Creates a new <code>TIntLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
* @param noEntryKey a <code>int</code> value that represents
* <tt>null</tt> for the Key set.
* @param noEntryValue a <code>long</code> value that represents
* <tt>null</tt> for the Value set.
*/
public TIntLongHashMap( int initialCapacity, float loadFactor,
int noEntryKey, long noEntryValue ) {
super( initialCapacity, loadFactor, noEntryKey, noEntryValue );
}
/**
* Creates a new <code>TIntLongHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param keys a <tt>int</tt> array containing the keys for the matching values.
* @param values a <tt>long</tt> array containing the values.
*/
public TIntLongHashMap( int[] keys, long[] values ) {
super( Math.max( keys.length, values.length ) );
int size = Math.min( keys.length, values.length );
for ( int i = 0; i < size; i++ ) {
this.put( keys[i], values[i] );
}
}
/**
* Creates a new <code>TIntLongHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param map a <tt>TIntLongMap</tt> that will be duplicated.
*/
public TIntLongHashMap( TIntLongMap map ) {
super( map.size() );
if ( map instanceof TIntLongHashMap ) {
TIntLongHashMap hashmap = ( TIntLongHashMap ) map;
this._loadFactor = hashmap._loadFactor;
this.no_entry_key = hashmap.no_entry_key;
this.no_entry_value = hashmap.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_key != ( int ) 0 ) {
Arrays.fill( _set, this.no_entry_key );
}
//noinspection RedundantCast
if ( this.no_entry_value != ( long ) 0 ) {
Arrays.fill( _values, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
putAll( map );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = new long[capacity];
return capacity;
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
/** {@inheritDoc} */
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
int oldKeys[] = _set;
long oldVals[] = _values;
byte oldStates[] = _states;
_set = new int[newCapacity];
_values = new long[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
int o = oldKeys[i];
int index = insertKey( o );
_values[index] = oldVals[i];
}
}
}
/** {@inheritDoc} */
public long put( int key, long value ) {
int index = insertKey( key );
return doPut( key, value, index );
}
/** {@inheritDoc} */
public long putIfAbsent( int key, long value ) {
int index = insertKey( key );
if (index < 0)
return _values[-index - 1];
return doPut( key, value, index );
}
private long doPut( int key, long value, int index ) {
long previous = no_entry_value;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public void putAll( Map<? extends Integer, ? extends Long> map ) {
ensureCapacity( map.size() );
// could optimize this for cases when map instanceof THashMap
for ( Map.Entry<? extends Integer, ? extends Long> entry : map.entrySet() ) {
this.put( entry.getKey().intValue(), entry.getValue().longValue() );
}
}
/** {@inheritDoc} */
public void putAll( TIntLongMap map ) {
ensureCapacity( map.size() );
TIntLongIterator iter = map.iterator();
while ( iter.hasNext() ) {
iter.advance();
this.put( iter.key(), iter.value() );
}
}
/** {@inheritDoc} */
public long get( int key ) {
int index = index( key );
return index < 0 ? no_entry_value : _values[index];
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, no_entry_key );
Arrays.fill( _values, 0, _values.length, no_entry_value );
Arrays.fill( _states, 0, _states.length, FREE );
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public long remove( int key ) {
long prev = no_entry_value;
int index = index( key );
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/** {@inheritDoc} */
protected void removeAt( int index ) {
_values[index] = no_entry_value;
super.removeAt( index ); // clear key, state; adjust size
}
/** {@inheritDoc} */
public TIntSet keySet() {
return new TKeyView();
}
/** {@inheritDoc} */
public int[] keys() {
int[] keys = new int[size()];
int[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
keys[j++] = k[i];
}
}
return keys;
}
/** {@inheritDoc} */
public int[] keys( int[] array ) {
int size = size();
if ( array.length < size ) {
array = new int[size];
}
int[] keys = _set;
byte[] states = _states;
for ( int i = keys.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = keys[i];
}
}
return array;
}
/** {@inheritDoc} */
public TLongCollection valueCollection() {
return new TValueView();
}
/** {@inheritDoc} */
public long[] values() {
long[] vals = new long[size()];
long[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
public long[] values( long[] array ) {
int size = size();
if ( array.length < size ) {
array = new long[size];
}
long[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = v[i];
}
}
return array;
}
/** {@inheritDoc} */
public boolean containsValue( long val ) {
byte[] states = _states;
long[] vals = _values;
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && val == vals[i] ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsKey( int key ) {
return contains( key );
}
/** {@inheritDoc} */
public TIntLongIterator iterator() {
return new TIntLongHashIterator( this );
}
/** {@inheritDoc} */
public boolean forEachKey( TIntProcedure procedure ) {
return forEach( procedure );
}
/** {@inheritDoc} */
public boolean forEachValue( TLongProcedure procedure ) {
byte[] states = _states;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean forEachEntry( TIntLongProcedure procedure ) {
byte[] states = _states;
int[] keys = _set;
long[] values = _values;
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public void transformValues( TLongFunction function ) {
byte[] states = _states;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
values[i] = function.execute( values[i] );
}
}
}
/** {@inheritDoc} */
public boolean retainEntries( TIntLongProcedure procedure ) {
boolean modified = false;
byte[] states = _states;
int[] keys = _set;
long[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
removeAt( i );
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/** {@inheritDoc} */
public boolean increment( int key ) {
return adjustValue( key, ( long ) 1 );
}
/** {@inheritDoc} */
public boolean adjustValue( int key, long amount ) {
int index = index( key );
if (index < 0) {
return false;
} else {
_values[index] += amount;
return true;
}
}
/** {@inheritDoc} */
public long adjustOrPutValue( int key, long adjust_amount, long put_amount ) {
int index = insertKey( key );
final boolean isNewMapping;
final long newValue;
if ( index < 0 ) {
index = -index -1;
newValue = ( _values[index] += adjust_amount );
isNewMapping = false;
} else {
newValue = ( _values[index] = put_amount );
isNewMapping = true;
}
byte previousState = _states[index];
if ( isNewMapping ) {
postInsertHook(consumeFreeSlot);
}
return newValue;
}
/** a view onto the keys of the map. */
protected class TKeyView implements TIntSet {
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntLongKeyHashIterator( TIntLongHashMap.this );
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_key;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( int entry ) {
return TIntLongHashMap.this.contains( entry );
}
/** {@inheritDoc} */
public int[] toArray() {
return TIntLongHashMap.this.keys();
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
return TIntLongHashMap.this.keys( dest );
}
/**
* Unsupported when operating upon a Key Set view of a TIntLongMap
* <p/>
* {@inheritDoc}
*/
public boolean add( int entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( int entry ) {
return no_entry_value != TIntLongHashMap.this.remove( entry );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int ele = ( ( Integer ) element ).intValue();
if ( ! TIntLongHashMap.this.containsKey( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TIntLongHashMap.this.containsKey( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int element : array ) {
if ( ! TIntLongHashMap.this.contains( element ) ) {
return false;
}
}
return true;
}
/**
* Unsupported when operating upon a Key Set view of a TIntLongMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( Collection<? extends Integer> collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TIntLongMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( TIntCollection collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TIntLongMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( int[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TIntLongHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
return TIntLongHashMap.this.forEachKey( procedure );
}
@Override
public boolean equals( Object other ) {
if (! (other instanceof TIntSet)) {
return false;
}
final TIntSet that = ( TIntSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachKey( new TIntProcedure() {
private boolean first = true;
public boolean execute( int key ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( key );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
/** a view onto the values of the map. */
protected class TValueView implements TLongCollection {
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TIntLongValueHashIterator( TIntLongHashMap.this );
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( long entry ) {
return TIntLongHashMap.this.containsValue( entry );
}
/** {@inheritDoc} */
public long[] toArray() {
return TIntLongHashMap.this.values();
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
return TIntLongHashMap.this.values( dest );
}
public boolean add( long entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( long entry ) {
long[] values = _values;
int[] set = _set;
for ( int i = values.length; i-- > 0; ) {
if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) {
removeAt( i );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long ele = ( ( Long ) element ).longValue();
if ( ! TIntLongHashMap.this.containsValue( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TIntLongHashMap.this.containsValue( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( long element : array ) {
if ( ! TIntLongHashMap.this.containsValue( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Long> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TLongCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( long[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, values[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TIntLongHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
return TIntLongHashMap.this.forEachValue( procedure );
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachValue( new TLongProcedure() {
private boolean first = true;
public boolean execute( long value ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( value );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
class TIntLongKeyHashIterator extends THashPrimitiveIterator implements TIntIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TIntLongKeyHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _set[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TIntLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TIntLongValueHashIterator extends THashPrimitiveIterator implements TLongIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TIntLongValueHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _values[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TIntLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TIntLongHashIterator extends THashPrimitiveIterator implements TIntLongIterator {
/**
* Creates an iterator over the specified map
*
* @param map the <tt>TIntLongHashMap</tt> we will be iterating over.
*/
TIntLongHashIterator( TIntLongHashMap map ) {
super( map );
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
public int key() {
return _set[_index];
}
/** {@inheritDoc} */
public long value() {
return _values[_index];
}
/** {@inheritDoc} */
public long setValue( long val ) {
long old = value();
_values[_index] = val;
return old;
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TIntLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
/** {@inheritDoc} */
@Override
public boolean equals( Object other ) {
if ( ! ( other instanceof TIntLongMap ) ) {
return false;
}
TIntLongMap that = ( TIntLongMap ) other;
if ( that.size() != this.size() ) {
return false;
}
long[] values = _values;
byte[] states = _states;
long this_no_entry_value = getNoEntryValue();
long that_no_entry_value = that.getNoEntryValue();
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
int key = _set[i];
long that_value = that.get( key );
long this_value = values[i];
if ( ( this_value != that_value ) &&
( this_value != this_no_entry_value ) &&
( that_value != that_no_entry_value ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int hashcode = 0;
byte[] states = _states;
for ( int i = _values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] ) ^
HashFunctions.hash( _values[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachEntry( new TIntLongProcedure() {
private boolean first = true;
public boolean execute( int key, long value ) {
if ( first ) first = false;
else buf.append( ", " );
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append( "}" );
return buf.toString();
}
/** {@inheritDoc} */
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeInt( _set[i] );
out.writeLong( _values[i] );
}
}
}
/** {@inheritDoc} */
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
int key = in.readInt();
long val = in.readLong();
put(key, val);
}
}
} // TIntLongHashMap
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
import gnu.trove.impl.Constants;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.hash.THash;
import gnu.trove.impl.hash.TObjectHash;
import gnu.trove.procedure.TObjectIntProcedure;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.iterator.TObjectIntIterator;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.iterator.hash.TObjectHashIterator;
import gnu.trove.function.TIntFunction;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.TIntCollection;
import java.io.*;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed Map implementation for Object keys and int values.
*
* Created: Sun Nov 4 08:52:45 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
*/
public class TObjectIntHashMap<K> extends TObjectHash<K>
implements TObjectIntMap<K>, Externalizable {
static final long serialVersionUID = 1L;
private final TObjectIntProcedure<K> PUT_ALL_PROC = new TObjectIntProcedure<K>() {
public boolean execute(K key, int value) {
put(key, value);
return true;
}
};
/** the values of the map */
protected transient int[] _values;
/** the value that represents null */
protected int no_entry_value;
/**
* Creates a new <code>TObjectIntHashMap</code> instance with the default
* capacity and load factor.
*/
public TObjectIntHashMap() {
super();
}
/**
* Creates a new <code>TObjectIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TObjectIntHashMap( int initialCapacity ) {
super( initialCapacity );
no_entry_value = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TObjectIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TObjectIntHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
no_entry_value = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TObjectIntHashMap</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param noEntryValue the value used to represent null.
*/
public TObjectIntHashMap( int initialCapacity, float loadFactor, int noEntryValue ) {
super( initialCapacity, loadFactor );
no_entry_value = noEntryValue;
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _values, no_entry_value );
}
}
/**
* Creates a new <code>TObjectIntHashMap</code> that contains the entries
* in the map passed to it.
*
* @param map the <tt>TObjectIntMap</tt> to be copied.
*/
public TObjectIntHashMap( TObjectIntMap<? extends K> map ) {
this( map.size(), 0.5f, map.getNoEntryValue() );
if ( map instanceof TObjectIntHashMap ) {
TObjectIntHashMap hashmap = ( TObjectIntHashMap ) map;
this._loadFactor = hashmap._loadFactor;
this.no_entry_value = hashmap.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_value != ( int ) 0 ) {
Arrays.fill( _values, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
putAll( map );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
public int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = new int[capacity];
return capacity;
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
//noinspection unchecked
K oldKeys[] = ( K[] ) _set;
int oldVals[] = _values;
_set = new Object[newCapacity];
Arrays.fill( _set, FREE );
_values = new int[newCapacity];
Arrays.fill( _values, no_entry_value );
for ( int i = oldCapacity; i-- > 0; ) {
if( oldKeys[i] != FREE && oldKeys[i] != REMOVED ) {
K o = oldKeys[i];
int index = insertKey(o);
if ( index < 0 ) {
throwObjectContractViolation( _set[ (-index -1) ], o);
}
_set[index] = o;
_values[index] = oldVals[i];
}
}
}
// Query Operations
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public boolean containsKey( Object key ) {
return contains( key );
}
/** {@inheritDoc} */
public boolean containsValue( int val ) {
Object[] keys = _set;
int[] vals = _values;
for ( int i = vals.length; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED && val == vals[i] ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public int get( Object key ) {
int index = index( key );
return index < 0 ? no_entry_value : _values[index];
}
// Modification Operations
/** {@inheritDoc} */
public int put( K key, int value ) {
int index = insertKey( key );
return doPut( value, index );
}
/** {@inheritDoc} */
public int putIfAbsent( K key, int value ) {
int index = insertKey(key);
if ( index < 0 )
return _values[-index - 1];
return doPut( value, index );
}
private int doPut( int value, int index ) {
int previous = no_entry_value;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
//noinspection unchecked
_values[index] = value;
if ( isNewMapping ) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public int remove( Object key ) {
int prev = no_entry_value;
int index = index(key);
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/**
* Removes the mapping at <tt>index</tt> from the map.
* This method is used internally and public mainly because
* of packaging reasons. Caveat Programmer.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_values[index] = no_entry_value;
super.removeAt( index ); // clear key, state; adjust size
}
// Bulk Operations
/** {@inheritDoc} */
public void putAll( Map<? extends K, ? extends Integer> map ) {
Set<? extends Map.Entry<? extends K,? extends Integer>> set = map.entrySet();
for ( Map.Entry<? extends K,? extends Integer> entry : set ) {
put( entry.getKey(), entry.getValue() );
}
}
/** {@inheritDoc} */
public void putAll( TObjectIntMap<? extends K> map ){
map.forEachEntry( PUT_ALL_PROC );
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, FREE );
Arrays.fill( _values, 0, _values.length, no_entry_value );
}
// Views
/** {@inheritDoc} */
public Set<K> keySet() {
return new KeyView();
}
/** {@inheritDoc} */
public Object[] keys() {
//noinspection unchecked
K[] keys = ( K[] ) new Object[size()];
Object[] k = _set;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( k[i] != FREE && k[i] != REMOVED ) {
//noinspection unchecked
keys[j++] = ( K ) k[i];
}
}
return keys;
}
/** {@inheritDoc} */
public K[] keys( K[] a ) {
int size = size();
if ( a.length < size ) {
//noinspection unchecked
a = ( K[] ) java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size );
}
Object[] k = _set;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( k[i] != FREE && k[i] != REMOVED ) {
//noinspection unchecked
a[j++] = ( K ) k[i];
}
}
return a;
}
/** {@inheritDoc} */
public TIntCollection valueCollection() {
return new TIntValueCollection();
}
/** {@inheritDoc} */
public int[] values() {
int[] vals = new int[size()];
int[] v = _values;
Object[] keys = _set;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
public int[] values( int[] array ) {
int size = size();
if ( array.length < size ) {
array = new int[size];
}
int[] v = _values;
Object[] keys = _set;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED ) {
array[j++] = v[i];
}
}
if ( array.length > size ) {
array[size] = no_entry_value;
}
return array;
}
/**
* @return an iterator over the entries in this map
*/
public TObjectIntIterator<K> iterator() {
return new TObjectIntHashIterator<K>( this );
}
/** {@inheritDoc} */
@SuppressWarnings({"RedundantCast"})
public boolean increment( K key ) {
//noinspection RedundantCast
return adjustValue( key, (int)1 );
}
/** {@inheritDoc} */
public boolean adjustValue( K key, int amount ) {
int index = index(key);
if ( index < 0 ) {
return false;
} else {
_values[index] += amount;
return true;
}
}
/** {@inheritDoc} */
public int adjustOrPutValue( final K key, final int adjust_amount,
final int put_amount ) {
int index = insertKey( key );
final boolean isNewMapping;
final int newValue;
if ( index < 0 ) {
index = -index -1;
newValue = ( _values[index] += adjust_amount );
isNewMapping = false;
} else {
newValue = ( _values[index] = put_amount );
isNewMapping = true;
}
//noinspection unchecked
if ( isNewMapping ) {
postInsertHook( consumeFreeSlot );
}
return newValue;
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TObjectProcedure<? super K> procedure ) {
return forEach( procedure );
}
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TIntProcedure procedure ) {
Object[] keys = _set;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED
&& ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOObjectIntProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
@SuppressWarnings({"unchecked"})
public boolean forEachEntry( TObjectIntProcedure<? super K> procedure ) {
Object[] keys = _set;
int[] values = _values;
for ( int i = keys.length; i-- > 0; ) {
if ( keys[i] != FREE
&& keys[i] != REMOVED
&& ! procedure.execute( ( K ) keys[i], values[i] ) ) {
return false;
}
}
return true;
}
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TObjectIntProcedure<? super K> procedure ) {
boolean modified = false;
//noinspection unchecked
K[] keys = ( K[] ) _set;
int[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( keys[i] != FREE
&& keys[i] != REMOVED
&& ! procedure.execute( keys[i], values[i] ) ) {
removeAt(i);
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TIntFunction</code> value
*/
public void transformValues( TIntFunction function ) {
Object[] keys = _set;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( keys[i] != null && keys[i] != REMOVED ) {
values[i] = function.execute( values[i] );
}
}
}
// Comparison and hashing
/**
* Compares this map with another map for equality of their stored
* entries.
*
* @param other an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean equals( Object other ) {
if ( ! ( other instanceof TObjectIntMap ) ) {
return false;
}
TObjectIntMap that = ( TObjectIntMap ) other;
if ( that.size() != this.size() ) {
return false;
}
try {
TObjectIntIterator iter = this.iterator();
while ( iter.hasNext() ) {
iter.advance();
Object key = iter.key();
int value = iter.value();
if ( value == no_entry_value ) {
if ( !( that.get( key ) == that.getNoEntryValue() &&
that.containsKey( key ) ) ) {
return false;
}
} else {
if ( value != that.get( key ) ) {
return false;
}
}
}
} catch ( ClassCastException ex ) {
// unused.
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
Object[] keys = _set;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED ) {
hashcode += HashFunctions.hash( values[i] ) ^
( keys[i] == null ? 0 : keys[i].hashCode() );
}
}
return hashcode;
}
/** a view onto the keys of the map. */
protected class KeyView extends MapBackedView<K> {
@SuppressWarnings({"unchecked"})
public Iterator<K> iterator() {
return new TObjectHashIterator( TObjectIntHashMap.this );
}
public boolean removeElement( K key ) {
return no_entry_value != TObjectIntHashMap.this.remove( key );
}
public boolean containsElement( K key ) {
return TObjectIntHashMap.this.contains( key );
}
}
private abstract class MapBackedView<E> extends AbstractSet<E>
implements Set<E>, Iterable<E> {
public abstract boolean removeElement( E key );
public abstract boolean containsElement( E key );
@SuppressWarnings({"unchecked"})
public boolean contains( Object key ) {
return containsElement( (E) key );
}
@SuppressWarnings({"unchecked"})
public boolean remove( Object o ) {
return removeElement( (E) o );
}
public void clear() {
TObjectIntHashMap.this.clear();
}
public boolean add( E obj ) {
throw new UnsupportedOperationException();
}
public int size() {
return TObjectIntHashMap.this.size();
}
public Object[] toArray() {
Object[] result = new Object[size()];
Iterator<E> e = iterator();
for ( int i = 0; e.hasNext(); i++ ) {
result[i] = e.next();
}
return result;
}
public <T> T[] toArray( T[] a ) {
int size = size();
if ( a.length < size ) {
//noinspection unchecked
a = (T[]) java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size );
}
Iterator<E> it = iterator();
Object[] result = a;
for ( int i = 0; i < size; i++ ) {
result[i] = it.next();
}
if ( a.length > size ) {
a[size] = null;
}
return a;
}
public boolean isEmpty() {
return TObjectIntHashMap.this.isEmpty();
}
public boolean addAll( Collection<? extends E> collection ) {
throw new UnsupportedOperationException();
}
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean changed = false;
Iterator<E> i = iterator();
while ( i.hasNext() ) {
if ( !collection.contains( i.next() ) ) {
i.remove();
changed = true;
}
}
return changed;
}
}
class TIntValueCollection implements TIntCollection {
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TObjectIntValueHashIterator();
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( int entry ) {
return TObjectIntHashMap.this.containsValue( entry );
}
/** {@inheritDoc} */
public int[] toArray() {
return TObjectIntHashMap.this.values();
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
return TObjectIntHashMap.this.values( dest );
}
public boolean add( int entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( int entry ) {
int[] values = _values;
Object[] set = _set;
for ( int i = values.length; i-- > 0; ) {
if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) {
removeAt( i );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int ele = ( ( Integer ) element ).intValue();
if ( ! TObjectIntHashMap.this.containsValue( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TObjectIntHashMap.this.containsValue( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int element : array ) {
if ( ! TObjectIntHashMap.this.containsValue( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Integer> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TIntCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( int[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] values = _values;
Object[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( set[i] != FREE
&& set[i] != REMOVED
&& ( Arrays.binarySearch( array, values[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TObjectIntHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
return TObjectIntHashMap.this.forEachValue( procedure );
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachValue( new TIntProcedure() {
private boolean first = true;
public boolean execute( int value ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( value );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
class TObjectIntValueHashIterator implements TIntIterator {
protected THash _hash = TObjectIntHashMap.this;
/**
* the number of elements this iterator believes are in the
* data structure it accesses.
*/
protected int _expectedSize;
/** the index used for iteration. */
protected int _index;
/** Creates an iterator over the specified map */
TObjectIntValueHashIterator() {
_expectedSize = _hash.size();
_index = _hash.capacity();
}
/** {@inheritDoc} */
public boolean hasNext() {
return nextIndex() >= 0;
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _values[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for
// bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TObjectIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
/**
* Sets the internal <tt>index</tt> so that the `next' object
* can be returned.
*/
protected final void moveToNextIndex() {
// doing the assignment && < 0 in one line shaves
// 3 opcodes...
if ( ( _index = nextIndex() ) < 0 ) {
throw new NoSuchElementException();
}
}
/**
* Returns the index of the next value in the data structure
* or a negative value if the iterator is exhausted.
*
* @return an <code>int</code> value
* @throws ConcurrentModificationException
* if the underlying
* collection's size has been modified since the iterator was
* created.
*/
protected final int nextIndex() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
Object[] set = TObjectIntHashMap.this._set;
int i = _index;
while ( i-- > 0 && ( set[i] == TObjectHash.FREE ||
set[i] == TObjectHash.REMOVED ) ) {
// do nothing
}
return i;
}
}
}
class TObjectIntHashIterator<K> extends TObjectHashIterator<K>
implements TObjectIntIterator<K> {
/** the collection being iterated over */
private final TObjectIntHashMap<K> _map;
public TObjectIntHashIterator( TObjectIntHashMap<K> map ) {
super( map );
this._map = map;
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public K key() {
return ( K ) _map._set[_index];
}
/** {@inheritDoc} */
public int value() {
return _map._values[_index];
}
/** {@inheritDoc} */
public int setValue( int val ) {
int old = value();
_map._values[_index] = val;
return old;
}
}
// Externalization
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_VALUE
out.writeInt( no_entry_value );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _set.length; i-- > 0; ) {
if ( _set[i] != REMOVED && _set[i] != FREE ) {
out.writeObject( _set[i] );
out.writeInt( _values[i] );
}
}
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_VALUE
no_entry_value = in.readInt();
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
//noinspection unchecked
K key = ( K ) in.readObject();
int val = in.readInt();
put(key, val);
}
}
/** {@inheritDoc} */
public String toString() {
final StringBuilder buf = new StringBuilder("{");
forEachEntry( new TObjectIntProcedure<K>() {
private boolean first = true;
public boolean execute( K key, int value ) {
if ( first ) first = false;
else buf.append( "," );
buf.append( key ).append( "=" ).append( value );
return true;
}
});
buf.append( "}" );
return buf.toString();
}
} // TObjectIntHashMap
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
import gnu.trove.impl.Constants;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.hash.THash;
import gnu.trove.impl.hash.TObjectHash;
import gnu.trove.procedure.TObjectLongProcedure;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.iterator.TObjectLongIterator;
import gnu.trove.iterator.TLongIterator;
import gnu.trove.iterator.hash.TObjectHashIterator;
import gnu.trove.function.TLongFunction;
import gnu.trove.map.TObjectLongMap;
import gnu.trove.TLongCollection;
import java.io.*;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed Map implementation for Object keys and long values.
*
* Created: Sun Nov 4 08:52:45 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
*/
public class TObjectLongHashMap<K> extends TObjectHash<K>
implements TObjectLongMap<K>, Externalizable {
static final long serialVersionUID = 1L;
private final TObjectLongProcedure<K> PUT_ALL_PROC = new TObjectLongProcedure<K>() {
public boolean execute(K key, long value) {
put(key, value);
return true;
}
};
/** the values of the map */
protected transient long[] _values;
/** the value that represents null */
protected long no_entry_value;
/**
* Creates a new <code>TObjectLongHashMap</code> instance with the default
* capacity and load factor.
*/
public TObjectLongHashMap() {
super();
}
/**
* Creates a new <code>TObjectLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TObjectLongHashMap( int initialCapacity ) {
super( initialCapacity );
no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TObjectLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TObjectLongHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TObjectLongHashMap</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param noEntryValue the value used to represent null.
*/
public TObjectLongHashMap( int initialCapacity, float loadFactor, long noEntryValue ) {
super( initialCapacity, loadFactor );
no_entry_value = noEntryValue;
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _values, no_entry_value );
}
}
/**
* Creates a new <code>TObjectLongHashMap</code> that contains the entries
* in the map passed to it.
*
* @param map the <tt>TObjectLongMap</tt> to be copied.
*/
public TObjectLongHashMap( TObjectLongMap<? extends K> map ) {
this( map.size(), 0.5f, map.getNoEntryValue() );
if ( map instanceof TObjectLongHashMap ) {
TObjectLongHashMap hashmap = ( TObjectLongHashMap ) map;
this._loadFactor = hashmap._loadFactor;
this.no_entry_value = hashmap.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_value != ( long ) 0 ) {
Arrays.fill( _values, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
putAll( map );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
public int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = new long[capacity];
return capacity;
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
//noinspection unchecked
K oldKeys[] = ( K[] ) _set;
long oldVals[] = _values;
_set = new Object[newCapacity];
Arrays.fill( _set, FREE );
_values = new long[newCapacity];
Arrays.fill( _values, no_entry_value );
for ( int i = oldCapacity; i-- > 0; ) {
if( oldKeys[i] != FREE && oldKeys[i] != REMOVED ) {
K o = oldKeys[i];
int index = insertKey(o);
if ( index < 0 ) {
throwObjectContractViolation( _set[ (-index -1) ], o);
}
_set[index] = o;
_values[index] = oldVals[i];
}
}
}
// Query Operations
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public boolean containsKey( Object key ) {
return contains( key );
}
/** {@inheritDoc} */
public boolean containsValue( long val ) {
Object[] keys = _set;
long[] vals = _values;
for ( int i = vals.length; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED && val == vals[i] ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public long get( Object key ) {
int index = index( key );
return index < 0 ? no_entry_value : _values[index];
}
// Modification Operations
/** {@inheritDoc} */
public long put( K key, long value ) {
int index = insertKey( key );
return doPut( value, index );
}
/** {@inheritDoc} */
public long putIfAbsent( K key, long value ) {
int index = insertKey(key);
if ( index < 0 )
return _values[-index - 1];
return doPut( value, index );
}
private long doPut( long value, int index ) {
long previous = no_entry_value;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
//noinspection unchecked
_values[index] = value;
if ( isNewMapping ) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public long remove( Object key ) {
long prev = no_entry_value;
int index = index(key);
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/**
* Removes the mapping at <tt>index</tt> from the map.
* This method is used internally and public mainly because
* of packaging reasons. Caveat Programmer.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_values[index] = no_entry_value;
super.removeAt( index ); // clear key, state; adjust size
}
// Bulk Operations
/** {@inheritDoc} */
public void putAll( Map<? extends K, ? extends Long> map ) {
Set<? extends Map.Entry<? extends K,? extends Long>> set = map.entrySet();
for ( Map.Entry<? extends K,? extends Long> entry : set ) {
put( entry.getKey(), entry.getValue() );
}
}
/** {@inheritDoc} */
public void putAll( TObjectLongMap<? extends K> map ){
map.forEachEntry( PUT_ALL_PROC );
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, FREE );
Arrays.fill( _values, 0, _values.length, no_entry_value );
}
// Views
/** {@inheritDoc} */
public Set<K> keySet() {
return new KeyView();
}
/** {@inheritDoc} */
public Object[] keys() {
//noinspection unchecked
K[] keys = ( K[] ) new Object[size()];
Object[] k = _set;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( k[i] != FREE && k[i] != REMOVED ) {
//noinspection unchecked
keys[j++] = ( K ) k[i];
}
}
return keys;
}
/** {@inheritDoc} */
public K[] keys( K[] a ) {
int size = size();
if ( a.length < size ) {
//noinspection unchecked
a = ( K[] ) java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size );
}
Object[] k = _set;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( k[i] != FREE && k[i] != REMOVED ) {
//noinspection unchecked
a[j++] = ( K ) k[i];
}
}
return a;
}
/** {@inheritDoc} */
public TLongCollection valueCollection() {
return new TLongValueCollection();
}
/** {@inheritDoc} */
public long[] values() {
long[] vals = new long[size()];
long[] v = _values;
Object[] keys = _set;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
public long[] values( long[] array ) {
int size = size();
if ( array.length < size ) {
array = new long[size];
}
long[] v = _values;
Object[] keys = _set;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED ) {
array[j++] = v[i];
}
}
if ( array.length > size ) {
array[size] = no_entry_value;
}
return array;
}
/**
* @return an iterator over the entries in this map
*/
public TObjectLongIterator<K> iterator() {
return new TObjectLongHashIterator<K>( this );
}
/** {@inheritDoc} */
@SuppressWarnings({"RedundantCast"})
public boolean increment( K key ) {
//noinspection RedundantCast
return adjustValue( key, (long)1 );
}
/** {@inheritDoc} */
public boolean adjustValue( K key, long amount ) {
int index = index(key);
if ( index < 0 ) {
return false;
} else {
_values[index] += amount;
return true;
}
}
/** {@inheritDoc} */
public long adjustOrPutValue( final K key, final long adjust_amount,
final long put_amount ) {
int index = insertKey( key );
final boolean isNewMapping;
final long newValue;
if ( index < 0 ) {
index = -index -1;
newValue = ( _values[index] += adjust_amount );
isNewMapping = false;
} else {
newValue = ( _values[index] = put_amount );
isNewMapping = true;
}
//noinspection unchecked
if ( isNewMapping ) {
postInsertHook( consumeFreeSlot );
}
return newValue;
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TObjectProcedure<? super K> procedure ) {
return forEach( procedure );
}
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TLongProcedure procedure ) {
Object[] keys = _set;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED
&& ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOObjectLongProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
@SuppressWarnings({"unchecked"})
public boolean forEachEntry( TObjectLongProcedure<? super K> procedure ) {
Object[] keys = _set;
long[] values = _values;
for ( int i = keys.length; i-- > 0; ) {
if ( keys[i] != FREE
&& keys[i] != REMOVED
&& ! procedure.execute( ( K ) keys[i], values[i] ) ) {
return false;
}
}
return true;
}
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TObjectLongProcedure<? super K> procedure ) {
boolean modified = false;
//noinspection unchecked
K[] keys = ( K[] ) _set;
long[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( keys[i] != FREE
&& keys[i] != REMOVED
&& ! procedure.execute( keys[i], values[i] ) ) {
removeAt(i);
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TLongFunction</code> value
*/
public void transformValues( TLongFunction function ) {
Object[] keys = _set;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( keys[i] != null && keys[i] != REMOVED ) {
values[i] = function.execute( values[i] );
}
}
}
// Comparison and hashing
/**
* Compares this map with another map for equality of their stored
* entries.
*
* @param other an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean equals( Object other ) {
if ( ! ( other instanceof TObjectLongMap ) ) {
return false;
}
TObjectLongMap that = ( TObjectLongMap ) other;
if ( that.size() != this.size() ) {
return false;
}
try {
TObjectLongIterator iter = this.iterator();
while ( iter.hasNext() ) {
iter.advance();
Object key = iter.key();
long value = iter.value();
if ( value == no_entry_value ) {
if ( !( that.get( key ) == that.getNoEntryValue() &&
that.containsKey( key ) ) ) {
return false;
}
} else {
if ( value != that.get( key ) ) {
return false;
}
}
}
} catch ( ClassCastException ex ) {
// unused.
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
Object[] keys = _set;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED ) {
hashcode += HashFunctions.hash( values[i] ) ^
( keys[i] == null ? 0 : keys[i].hashCode() );
}
}
return hashcode;
}
/** a view onto the keys of the map. */
protected class KeyView extends MapBackedView<K> {
@SuppressWarnings({"unchecked"})
public Iterator<K> iterator() {
return new TObjectHashIterator( TObjectLongHashMap.this );
}
public boolean removeElement( K key ) {
return no_entry_value != TObjectLongHashMap.this.remove( key );
}
public boolean containsElement( K key ) {
return TObjectLongHashMap.this.contains( key );
}
}
private abstract class MapBackedView<E> extends AbstractSet<E>
implements Set<E>, Iterable<E> {
public abstract boolean removeElement( E key );
public abstract boolean containsElement( E key );
@SuppressWarnings({"unchecked"})
public boolean contains( Object key ) {
return containsElement( (E) key );
}
@SuppressWarnings({"unchecked"})
public boolean remove( Object o ) {
return removeElement( (E) o );
}
public void clear() {
TObjectLongHashMap.this.clear();
}
public boolean add( E obj ) {
throw new UnsupportedOperationException();
}
public int size() {
return TObjectLongHashMap.this.size();
}
public Object[] toArray() {
Object[] result = new Object[size()];
Iterator<E> e = iterator();
for ( int i = 0; e.hasNext(); i++ ) {
result[i] = e.next();
}
return result;
}
public <T> T[] toArray( T[] a ) {
int size = size();
if ( a.length < size ) {
//noinspection unchecked
a = (T[]) java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size );
}
Iterator<E> it = iterator();
Object[] result = a;
for ( int i = 0; i < size; i++ ) {
result[i] = it.next();
}
if ( a.length > size ) {
a[size] = null;
}
return a;
}
public boolean isEmpty() {
return TObjectLongHashMap.this.isEmpty();
}
public boolean addAll( Collection<? extends E> collection ) {
throw new UnsupportedOperationException();
}
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean changed = false;
Iterator<E> i = iterator();
while ( i.hasNext() ) {
if ( !collection.contains( i.next() ) ) {
i.remove();
changed = true;
}
}
return changed;
}
}
class TLongValueCollection implements TLongCollection {
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TObjectLongValueHashIterator();
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( long entry ) {
return TObjectLongHashMap.this.containsValue( entry );
}
/** {@inheritDoc} */
public long[] toArray() {
return TObjectLongHashMap.this.values();
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
return TObjectLongHashMap.this.values( dest );
}
public boolean add( long entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( long entry ) {
long[] values = _values;
Object[] set = _set;
for ( int i = values.length; i-- > 0; ) {
if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) {
removeAt( i );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long ele = ( ( Long ) element ).longValue();
if ( ! TObjectLongHashMap.this.containsValue( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TObjectLongHashMap.this.containsValue( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( long element : array ) {
if ( ! TObjectLongHashMap.this.containsValue( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Long> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TLongCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( long[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] values = _values;
Object[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( set[i] != FREE
&& set[i] != REMOVED
&& ( Arrays.binarySearch( array, values[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TObjectLongHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
return TObjectLongHashMap.this.forEachValue( procedure );
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachValue( new TLongProcedure() {
private boolean first = true;
public boolean execute( long value ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( value );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
class TObjectLongValueHashIterator implements TLongIterator {
protected THash _hash = TObjectLongHashMap.this;
/**
* the number of elements this iterator believes are in the
* data structure it accesses.
*/
protected int _expectedSize;
/** the index used for iteration. */
protected int _index;
/** Creates an iterator over the specified map */
TObjectLongValueHashIterator() {
_expectedSize = _hash.size();
_index = _hash.capacity();
}
/** {@inheritDoc} */
public boolean hasNext() {
return nextIndex() >= 0;
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _values[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for
// bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TObjectLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
/**
* Sets the internal <tt>index</tt> so that the `next' object
* can be returned.
*/
protected final void moveToNextIndex() {
// doing the assignment && < 0 in one line shaves
// 3 opcodes...
if ( ( _index = nextIndex() ) < 0 ) {
throw new NoSuchElementException();
}
}
/**
* Returns the index of the next value in the data structure
* or a negative value if the iterator is exhausted.
*
* @return an <code>int</code> value
* @throws ConcurrentModificationException
* if the underlying
* collection's size has been modified since the iterator was
* created.
*/
protected final int nextIndex() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
Object[] set = TObjectLongHashMap.this._set;
int i = _index;
while ( i-- > 0 && ( set[i] == TObjectHash.FREE ||
set[i] == TObjectHash.REMOVED ) ) {
// do nothing
}
return i;
}
}
}
class TObjectLongHashIterator<K> extends TObjectHashIterator<K>
implements TObjectLongIterator<K> {
/** the collection being iterated over */
private final TObjectLongHashMap<K> _map;
public TObjectLongHashIterator( TObjectLongHashMap<K> map ) {
super( map );
this._map = map;
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public K key() {
return ( K ) _map._set[_index];
}
/** {@inheritDoc} */
public long value() {
return _map._values[_index];
}
/** {@inheritDoc} */
public long setValue( long val ) {
long old = value();
_map._values[_index] = val;
return old;
}
}
// Externalization
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_VALUE
out.writeLong( no_entry_value );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _set.length; i-- > 0; ) {
if ( _set[i] != REMOVED && _set[i] != FREE ) {
out.writeObject( _set[i] );
out.writeLong( _values[i] );
}
}
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_VALUE
no_entry_value = in.readLong();
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
//noinspection unchecked
K key = ( K ) in.readObject();
long val = in.readLong();
put(key, val);
}
}
/** {@inheritDoc} */
public String toString() {
final StringBuilder buf = new StringBuilder("{");
forEachEntry( new TObjectLongProcedure<K>() {
private boolean first = true;
public boolean execute( K key, long value ) {
if ( first ) first = false;
else buf.append( "," );
buf.append( key ).append( "=" ).append( value );
return true;
}
});
buf.append( "}" );
return buf.toString();
}
} // TObjectLongHashMap
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
import gnu.trove.function.TObjectFunction;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.hash.TObjectHash;
import gnu.trove.iterator.hash.TObjectHashIterator;
import gnu.trove.map.TMap;
import gnu.trove.procedure.TObjectObjectProcedure;
import gnu.trove.procedure.TObjectProcedure;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.*;
/**
* An implementation of the Map interface which uses an open addressed
* hash table to store its contents.
* <p/>
* Created: Sun Nov 4 08:52:45 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: THashMap.java,v 1.1.2.8 2010/03/02 04:09:50 robeden Exp $
*/
public class THashMap<K, V> extends TObjectHash<K> implements TMap<K, V>, Externalizable {
static final long serialVersionUID = 1L;
/**
* the values of the map
*/
protected transient V[] _values;
/**
* Creates a new <code>THashMap</code> instance with the default
* capacity and load factor.
*/
public THashMap() {
super();
}
/**
* Creates a new <code>THashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public THashMap(int initialCapacity) {
super(initialCapacity);
}
/**
* Creates a new <code>THashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public THashMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}
/**
* Creates a new <code>THashMap</code> instance which contains the
* key/value pairs in <tt>map</tt>.
*
* @param map a <code>Map</code> value
*/
public THashMap(Map<? extends K, ? extends V> map) {
this(map.size());
putAll(map);
}
/**
* Creates a new <code>THashMap</code> instance which contains the
* key/value pairs in <tt>map</tt>.
*
* @param map a <code>Map</code> value
*/
public THashMap(THashMap<? extends K, ? extends V> map) {
this(map.size());
putAll(map);
}
/**
* initialize the value array of the map.
*
* @param initialCapacity an <code>int</code> value
* @return an <code>int</code> value
*/
public int setUp(int initialCapacity) {
int capacity;
capacity = super.setUp(initialCapacity);
//noinspection unchecked
_values = (V[]) new Object[capacity];
return capacity;
}
/**
* Inserts a key/value pair into the map.
*
* @param key an <code>Object</code> value
* @param value an <code>Object</code> value
* @return the previous value associated with <tt>key</tt>,
* or {@code null} if none was found.
*/
public V put(K key, V value) {
// insertKey() inserts the key if a slot if found and returns the index
int index = insertKey(key);
return doPut(value, index);
}
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key an <code>Object</code> value
* @param value an <code>Object</code> value
* @return the previous value associated with <tt>key</tt>,
* or {@code null} if none was found.
*/
public V putIfAbsent(K key, V value) {
// insertKey() inserts the key if a slot if found and returns the index
int index = insertKey(key);
if (index < 0) {
return _values[-index - 1];
}
return doPut(value, index);
}
private V doPut(V value, int index) {
V previous = null;
boolean isNewMapping = true;
if (index < 0) {
index = -index - 1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook(consumeFreeSlot);
}
return previous;
}
/**
* Compares this map with another map for equality of their stored
* entries.
*
* @param other an <code>Object</code> value
* @return a <code>boolean</code> value
*/
@SuppressWarnings({"unchecked", "SimplifiableIfStatement"})
public boolean equals(Object other) {
if (!(other instanceof Map)) {
return false;
}
Map<K, V> that = (Map<K, V>) other;
if (that.size() != this.size()) {
return false;
}
return forEachEntry(new EqProcedure<K, V>(that));
}
public int hashCode() {
HashProcedure p = new HashProcedure();
forEachEntry(p);
return p.getHashCode();
}
public String toString() {
final StringBuilder buf = new StringBuilder("{");
forEachEntry(new TObjectObjectProcedure<K, V>() {
private boolean first = true;
public boolean execute(K key, V value) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append("}");
return buf.toString();
}
private final class HashProcedure implements TObjectObjectProcedure<K, V> {
private int h = 0;
public int getHashCode() {
return h;
}
public final boolean execute(K key, V value) {
h += HashFunctions.hash(key) ^ (value == null ? 0 : value.hashCode());
return true;
}
}
private final class EqProcedure<K, V> implements TObjectObjectProcedure<K, V> {
private final Map<K, V> _otherMap;
EqProcedure(Map<K, V> otherMap) {
_otherMap = otherMap;
}
public final boolean execute(K key, V value) {
// Check to make sure the key is there. This avoids problems that come up with
// null values. Since it is only caused in that cause, only do this when the
// value is null (to avoid extra work).
if (value == null && !_otherMap.containsKey(key)) {
return false;
}
V oValue = _otherMap.get(key);
return oValue == value || (oValue != null &&
THashMap.this.equals(oValue, value));
}
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey(TObjectProcedure<? super K> procedure) {
return forEach(procedure);
}
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue(TObjectProcedure<? super V> procedure) {
V[] values = _values;
Object[] set = _set;
for (int i = values.length; i-- > 0;) {
if (set[i] != FREE
&& set[i] != REMOVED
&& !procedure.execute(values[i])) {
return false;
}
}
return true;
}
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TObjectObjectProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
@SuppressWarnings({"unchecked"})
public boolean forEachEntry(TObjectObjectProcedure<? super K, ? super V> procedure) {
Object[] keys = _set;
V[] values = _values;
for (int i = keys.length; i-- > 0;) {
if (keys[i] != FREE
&& keys[i] != REMOVED
&& !procedure.execute((K) keys[i], values[i])) {
return false;
}
}
return true;
}
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
@SuppressWarnings({"unchecked"})
public boolean retainEntries(TObjectObjectProcedure<? super K, ? super V> procedure) {
boolean modified = false;
Object[] keys = _set;
V[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for (int i = keys.length; i-- > 0;) {
if (keys[i] != FREE
&& keys[i] != REMOVED
&& !procedure.execute((K) keys[i], values[i])) {
removeAt(i);
modified = true;
}
}
} finally {
reenableAutoCompaction(true);
}
return modified;
}
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TObjectFunction</code> value
*/
public void transformValues(TObjectFunction<V, V> function) {
V[] values = _values;
Object[] set = _set;
for (int i = values.length; i-- > 0;) {
if (set[i] != FREE && set[i] != REMOVED) {
values[i] = function.execute(values[i]);
}
}
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
@SuppressWarnings({"unchecked"})
protected void rehash(int newCapacity) {
int oldCapacity = _set.length;
int oldSize = size();
Object oldKeys[] = _set;
V oldVals[] = _values;
_set = new Object[newCapacity];
Arrays.fill(_set, FREE);
_values = (V[]) new Object[newCapacity];
// Process entries from the old array, skipping free and removed slots. Put the
// values into the appropriate place in the new array.
int count = 0;
for (int i = oldCapacity; i-- > 0;) {
Object o = oldKeys[i];
if (o == FREE || o == REMOVED) continue;
int index = insertKey((K) o);
if (index < 0) {
throwObjectContractViolation(_set[(-index - 1)], o, size(), oldSize, oldKeys);
}
_values[index] = oldVals[i];
//
count++;
}
// Last check: size before and after should be the same
reportPotentialConcurrentMod(size(), oldSize);
}
/**
* retrieves the value for <tt>key</tt>
*
* @param key an <code>Object</code> value
* @return the value of <tt>key</tt> or null if no such mapping exists.
*/
@SuppressWarnings({"unchecked"})
public V get(Object key) {
int index = index(key);
return index < 0 ? null : _values[index];
}
/**
* Empties the map.
*/
public void clear() {
if (size() == 0) {
return; // optimization
}
super.clear();
Arrays.fill(_set, 0, _set.length, FREE);
Arrays.fill(_values, 0, _values.length, null);
}
/**
* Deletes a key/value pair from the map.
*
* @param key an <code>Object</code> value
* @return an <code>Object</code> value
*/
@SuppressWarnings({"unchecked"})
public V remove(Object key) {
V prev = null;
int index = index(key);
if (index >= 0) {
prev = _values[index];
removeAt(index); // clear key,state; adjust size
}
return prev;
}
/**
* removes the mapping at <tt>index</tt> from the map.
*
* @param index an <code>int</code> value
*/
public void removeAt(int index) {
_values[index] = null;
super.removeAt(index); // clear key, state; adjust size
}
/**
* Returns a view on the values of the map.
*
* @return a <code>Collection</code> value
*/
public Collection<V> values() {
return new ValueView();
}
/**
* returns a Set view on the keys of the map.
*
* @return a <code>Set</code> value
*/
public Set<K> keySet() {
return new KeyView();
}
/**
* Returns a Set view on the entries of the map.
*
* @return a <code>Set</code> value
*/
public Set<Map.Entry<K, V>> entrySet() {
return new EntryView();
}
/**
* checks for the presence of <tt>val</tt> in the values of the map.
*
* @param val an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean containsValue(Object val) {
Object[] set = _set;
V[] vals = _values;
// special case null values so that we don't have to
// perform null checks before every call to equals()
if (null == val) {
for (int i = vals.length; i-- > 0;) {
if ((set[i] != FREE && set[i] != REMOVED) &&
val == vals[i]) {
return true;
}
}
} else {
for (int i = vals.length; i-- > 0;) {
if ((set[i] != FREE && set[i] != REMOVED) &&
(val == vals[i] || equals(val, vals[i]))) {
return true;
}
}
} // end of else
return false;
}
/**
* checks for the present of <tt>key</tt> in the keys of the map.
*
* @param key an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean containsKey(Object key) {
//noinspection unchecked
return contains(key);
}
/**
* copies the key/value mappings in <tt>map</tt> into this map.
*
* @param map a <code>Map</code> value
*/
public void putAll(Map<? extends K, ? extends V> map) {
ensureCapacity(map.size());
// could optimize this for cases when map instanceof THashMap
for (Map.Entry<? extends K, ? extends V> e : map.entrySet()) {
put(e.getKey(), e.getValue());
}
}
/**
* a view onto the values of the map.
*/
protected class ValueView extends MapBackedView<V> {
@SuppressWarnings({"unchecked"})
public Iterator<V> iterator() {
return new TObjectHashIterator(THashMap.this) {
protected V objectAtIndex(int index) {
return _values[index];
}
};
}
public boolean containsElement(V value) {
return containsValue(value);
}
public boolean removeElement(V value) {
Object[] values = _values;
Object[] set = _set;
for (int i = values.length; i-- > 0;) {
if ((set[i] != FREE && set[i] != REMOVED) &&
value == values[i] ||
(null != values[i] && THashMap.this.equals(values[i], value))) {
removeAt(i);
return true;
}
}
return false;
}
}
/**
* a view onto the entries of the map.
*/
protected class EntryView extends MapBackedView<Map.Entry<K, V>> {
private final class EntryIterator extends TObjectHashIterator {
EntryIterator(THashMap<K, V> map) {
super(map);
}
@SuppressWarnings({"unchecked"})
public Entry objectAtIndex(final int index) {
return new Entry((K) _set[index], _values[index], index);
}
}
@SuppressWarnings({"unchecked"})
public Iterator<Map.Entry<K, V>> iterator() {
return new EntryIterator(THashMap.this);
}
public boolean removeElement(Map.Entry<K, V> entry) {
if (entry == null) return false;
// have to effectively reimplement Map.remove here
// because we need to return true/false depending on
// whether the removal took place. Since the Entry's
// value can be null, this means that we can't rely
// on the value of the object returned by Map.remove()
// to determine whether a deletion actually happened.
//
// Note also that the deletion is only legal if
// both the key and the value match.
V val;
int index;
K key = keyForEntry(entry);
index = index(key);
if (index >= 0) {
val = valueForEntry(entry);
if (val == _values[index] ||
(null != val && THashMap.this.equals(val, _values[index]))) {
removeAt(index); // clear key,state; adjust size
return true;
}
}
return false;
}
public boolean containsElement(Map.Entry<K, V> entry) {
V val = get(keyForEntry(entry));
V entryValue = entry.getValue();
return entryValue == val ||
(null != val && THashMap.this.equals(val, entryValue));
}
protected V valueForEntry(Map.Entry<K, V> entry) {
return entry.getValue();
}
protected K keyForEntry(Map.Entry<K, V> entry) {
return entry.getKey();
}
}
private abstract class MapBackedView<E> extends AbstractSet<E>
implements Set<E>, Iterable<E> {
public abstract Iterator<E> iterator();
public abstract boolean removeElement(E key);
public abstract boolean containsElement(E key);
@SuppressWarnings({"unchecked"})
public boolean contains(Object key) {
return containsElement((E) key);
}
@SuppressWarnings({"unchecked"})
public boolean remove(Object o) {
try {
return removeElement((E) o);
} catch (ClassCastException ex) {
return false;
}
}
// public boolean containsAll( Collection<?> collection ) {
// for ( Object element : collection ) {
// if ( !contains( element ) ) {
// return false;
// }
// }
// return true;
// }
public void clear() {
THashMap.this.clear();
}
public boolean add(E obj) {
throw new UnsupportedOperationException();
}
public int size() {
return THashMap.this.size();
}
public Object[] toArray() {
Object[] result = new Object[size()];
Iterator<E> e = iterator();
for (int i = 0; e.hasNext(); i++) {
result[i] = e.next();
}
return result;
}
@SuppressWarnings({"unchecked"})
public <T> T[] toArray(T[] a) {
int size = size();
if (a.length < size) {
a = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
}
Iterator<E> it = iterator();
Object[] result = a;
for (int i = 0; i < size; i++) {
result[i] = it.next();
}
if (a.length > size) {
a[size] = null;
}
return a;
}
public boolean isEmpty() {
return THashMap.this.isEmpty();
}
public boolean addAll(Collection<? extends E> collection) {
throw new UnsupportedOperationException();
}
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll(Collection<?> collection) {
boolean changed = false;
Iterator<E> i = iterator();
while (i.hasNext()) {
if (!collection.contains(i.next())) {
i.remove();
changed = true;
}
}
return changed;
}
public String toString() {
Iterator<E> i = iterator();
if (!i.hasNext()) return "{}";
StringBuilder sb = new StringBuilder();
sb.append('{');
for (; ;) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (!i.hasNext()) return sb.append('}').toString();
sb.append(", ");
}
}
}
/**
* a view onto the keys of the map.
*/
protected class KeyView extends MapBackedView<K> {
@SuppressWarnings({"unchecked"})
public Iterator<K> iterator() {
return new TObjectHashIterator<K>(THashMap.this);
}
public boolean removeElement(K key) {
return null != THashMap.this.remove(key);
}
public boolean containsElement(K key) {
return THashMap.this.contains(key);
}
}
final class Entry implements Map.Entry<K, V> {
private K key;
private V val;
private final int index;
Entry(final K key, V value, final int index) {
this.key = key;
this.val = value;
this.index = index;
}
public K getKey() {
return key;
}
public V getValue() {
return val;
}
public V setValue(V o) {
if (_values[index] != val) {
throw new ConcurrentModificationException();
}
// need to return previous value
V retval = val;
// update this entry's value, in case setValue is called again
_values[index] = o;
val = o;
return retval;
}
public boolean equals(Object o) {
if (o instanceof Map.Entry) {
Map.Entry<K, V> e1 = this;
Map.Entry e2 = (Map.Entry) o;
return (THashMap.this.equals(e1.getKey(), e2.getKey()))
&& (THashMap.this.equals(e1.getValue(), e1.getValue()));
}
return false;
}
public int hashCode() {
return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode());
}
@Override
public String toString() {
return key + "=" + val;
}
}
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte(1);
// NOTE: Super was not written in version 0
super.writeExternal(out);
// NUMBER OF ENTRIES
out.writeInt(_size);
// ENTRIES
for (int i = _set.length; i-- > 0;) {
if (_set[i] != REMOVED && _set[i] != FREE) {
out.writeObject(_set[i]);
out.writeObject(_values[i]);
}
}
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
// VERSION
byte version = in.readByte();
// NOTE: super was not written in version 0
if (version != 0) {
super.readExternal(in);
}
// NUMBER OF ENTRIES
int size = in.readInt();
setUp(size);
// ENTRIES
while (size-- > 0) {
//noinspection unchecked
K key = (K) in.readObject();
//noinspection unchecked
V val = (V) in.readObject();
put(key, val);
}
}
} // THashMap
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011, Rob Eden All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
import gnu.trove.function.TObjectFunction;
import gnu.trove.procedure.TObjectObjectProcedure;
import gnu.trove.procedure.TObjectProcedure;
import java.util.Map;
/**
* Interface extension to {@link Map} which adds Trove-specific features.
*/
public interface TMap<K,V> extends Map<K,V> {
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key an <code>Object</code> value
* @param value an <code>Object</code> value
* @return the previous value associated with <tt>key</tt>,
* or {@code null} if none was found.
*/
public V putIfAbsent(K key, V value);
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey(TObjectProcedure<? super K> procedure);
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue(TObjectProcedure<? super V> procedure);
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TObjectObjectProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
@SuppressWarnings({"unchecked"})
public boolean forEachEntry(TObjectObjectProcedure<? super K, ? super V> procedure);
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
@SuppressWarnings({"unchecked"})
public boolean retainEntries(TObjectObjectProcedure<? super K, ? super V> procedure);
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TObjectFunction</code> value
*/
public void transformValues(TObjectFunction<V, V> function);
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
import gnu.trove.TLongCollection;
import gnu.trove.function.TLongFunction;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.procedure.TObjectLongProcedure;
import gnu.trove.iterator.TObjectLongIterator;
import java.util.Map;
import java.util.Set;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for a primitive map of Object keys and long values.
*/
public interface TObjectLongMap<K> {
// Query Operations
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
long getNoEntryValue();
/**
* Returns the number of key-value mappings in this map. If the
* map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of key-value mappings in this map
*/
int size();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this map contains a mapping for the specified
* key. More formally, returns <tt>true</tt> if and only if
* this map contains a mapping for a key <tt>k</tt> such that
* <tt>(key==null ? k==null : key.equals(k))</tt>. (There can be
* at most one such mapping.)
*
* @param key key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
boolean containsKey( Object key );
/**
* Returns <tt>true</tt> if this map maps one or more keys to the
* specified value. More formally, returns <tt>true</tt> if and only if
* this map contains at least one mapping to a value <tt>v</tt> such that
* <tt>(value==no_entry_value ? v==no_entry_value : value.equals(v))</tt>. This operation
* will probably require time linear in the map size for most
* implementations of the <tt>Map</tt> interface.
*<p/>
* Note that no_entry_value is the result of {@link #getNoEntryValue()} and represents
* null for this map instance.
*
* @param value <tt>long</tt> value whose presence in this map is to be tested
* @return <tt>true</tt> if this map maps one or more keys to the
* specified value
* @throws ClassCastException if the value is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified value is null and this
* map does not permit null values (optional)
*/
boolean containsValue( long value );
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>If this map permits null values, then a return value of
* {@code null} does not <i>necessarily</i> indicate that the map
* contains no mapping for the key; it's also possible that the map
* explicitly maps the key to {@code null}. The {@link #containsKey
* containsKey} operation may be used to distinguish these two cases.
*
* @param key the key whose associated value is to be returned
* @return the <tt>long</tt> value to which the specified key is mapped, or
* {@code null} if this map contains no mapping for the key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
long get( Object key );
// Modification Operations
/**
* Associates the specified value with the specified key in this map
* (optional operation). If the map previously contained a mapping for
* the key, the old value is replaced by the specified value. (A map
* <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
* if {@link #containsKey(Object) m.containsKey(k)} would return
* <tt>true</tt>.)
*
* @param key key with which the specified value is to be associated
* @param value an <tt>long</tt> value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>no_entry_value</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>no_entry_value</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>,
* if the implementation supports <tt>null</tt> values.)
* @throws UnsupportedOperationException if the <tt>put</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* @throws NullPointerException if the specified key or value is null
* and this map does not permit null keys or values
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* @see #getNoEntryValue()
*/
long put( K key, long value);
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key key with which the specified value is to be associated
* @param value an <tt>long</tt> value to be associated with the specified key
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
long putIfAbsent( K key, long value );
/**
* Removes the mapping for a key from this map if it is present
* (optional operation). More formally, if this map contains a mapping
* from key <tt>k</tt> to value <tt>v</tt> such that
* <code>(key==null ? k==null : key.equals(k))</code>, that mapping
* is removed. (The map can contain at most one such mapping.)
*
* <p>Returns the value to which this map previously associated the key,
* or <tt>null</tt> if the map contained no mapping for the key.
*
* <p>If this map permits null values, then a return value of
* <tt>null</tt> does not <i>necessarily</i> indicate that the map
* contained no mapping for the key; it's also possible that the map
* explicitly mapped the key to <tt>null</tt>.
*
* <p>The map will not contain a mapping for the specified key once the
* call returns.
*
* @param key key whose mapping is to be removed from the map
* @return the previous <tt>long</tt> value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this map
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this
* map does not permit null keys (optional)
*/
long remove( Object key );
// Bulk Operations
/**
* Copies all of the mappings from the specified map to this map
* (optional operation). The effect of this call is equivalent to that
* of calling {@link #put(Object,long) put(k, v)} on this map once
* for each mapping from key <tt>k</tt> to value <tt>v</tt> in the
* specified map. The behavior of this operation is undefined if the
* specified map is modified while the operation is in progress.
*
* @param m mappings to be stored in this map
* @throws UnsupportedOperationException if the <tt>putAll</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of a key or value in the
* specified map prevents it from being stored in this map
* @throws NullPointerException if the specified map is null, or if
* this map does not permit null keys or values, and the
* specified map contains null keys or values
* @throws IllegalArgumentException if some property of a key or value in
* the specified map prevents it from being stored in this map
*/
void putAll( Map<? extends K, ? extends Long> m);
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
void putAll( TObjectLongMap<? extends K> map );
/**
* Removes all of the mappings from this map (optional operation).
* The map will be empty after this call returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this map
*/
void clear();
// Views
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*
* @return a set view of the keys contained in this map
*/
Set<K> keySet();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @return a copy of the keys of the map as an array.
*/
Object[] keys();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
K[] keys( K[] array );
/**
* Returns a {@link TLongCollection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own <tt>remove</tt> operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>TLongIterator.remove</tt>,
* <tt>TLongCollection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a collection view of the values contained in this map
*/
TLongCollection valueCollection();
/**
* Returns the values of the map as an array of <tt>long</tt> values.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @return the values of the map as an array of <tt>long</tt> values.
*/
long[] values();
/**
* Returns the values of the map using an existing array.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>long</tt> values.
*/
long[] values( long[] array );
/**
* Returns a <tt>TObjectLongIterator</tt> with access to this map's keys and values.
*
* @return a <tt>TObjectLongIterator</tt> with access to this map's keys and values.
*/
public TObjectLongIterator<K> iterator();
/**
* Increments the primitive value mapped to key by 1
*
* @param key the key of the value to increment
* @return true if a mapping was found and modified.
*/
public boolean increment( K key );
/**
* Adjusts the primitive value mapped to key.
*
* @param key the key of the value to increment
* @param amount the amount to adjust the value by.
* @return true if a mapping was found and modified.
*/
public boolean adjustValue( K key, long amount );
/**
* Adjusts the primitive value mapped to the key if the key is present in the map.
* Otherwise, the <tt>initial_value</tt> is put in the map.
*
* @param key the key of the value to increment
* @param adjust_amount the amount to adjust the value by
* @param put_amount the value put into the map if the key is not initial present
*
* @return the value present in the map after the adjustment or put operation
*/
public long adjustOrPutValue( K key, long adjust_amount, long put_amount );
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TObjectProcedure<? super K> procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TLongProcedure procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOObjectLongProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TObjectLongProcedure<? super K> procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TLongFunction</code> value
*/
public void transformValues( TLongFunction function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TObjectLongProcedure<? super K> procedure );
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
boolean equals( Object o );
/**
* Returns the hash code value for this map. The hash code of a map is
* defined to be the sum of the hash codes of each entry in the map's
* <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
* implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
* <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this map
* @see Object#equals(Object)
* @see #equals(Object)
*/
int hashCode();
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
import gnu.trove.iterator.TIntObjectIterator;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.TIntObjectProcedure;
import gnu.trove.function.TObjectFunction;
import gnu.trove.set.TIntSet;
import java.util.Collection;
import java.util.Map;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for a primitive map of int keys and Object values.
*/
public interface TIntObjectMap<V> {
// Query Operations
/**
* Returns the value that represents null in the {@link #keySet()}.
* The default value is generally zero, but can be changed during
* construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
int getNoEntryKey();
/**
* Returns the number of key-value mappings in this map. If the
* map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of key-value mappings in this map
*/
int size();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this map contains a mapping for the specified
* key. More formally, returns <tt>true</tt> if and only if
* this map contains a mapping for a key <tt>k</tt> such that
* <tt>key.equals(k)</tt>. (There can be at most one such mapping.)
*
* @param key key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
boolean containsKey( int key );
/**
* Returns <tt>true</tt> if this map maps one or more keys to the
* specified value. More formally, returns <tt>true</tt> if and only if
* this map contains at least one mapping to a value <tt>v</tt> such that
* <tt>(value==null ? v==null : value.equals(v))</tt>. This operation
* will probably require time linear in the map size for most
* implementations of the <tt>Map</tt> interface.
*
* @param value value whose presence in this map is to be tested
* @return <tt>true</tt> if this map maps one or more keys to the
* specified value
* @throws ClassCastException if the value is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified value is null and this
* map does not permit null values (optional)
*/
boolean containsValue( Object value );
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>If this map permits null values, then a return value of
* {@code null} does not <i>necessarily</i> indicate that the map
* contains no mapping for the key; it's also possible that the map
* explicitly maps the key to {@code null}. The {@link #containsKey
* containsKey} operation may be used to distinguish these two cases.
*
* @param key the key whose associated value is to be returned
* @return the <tt>int</tt> value to which the specified key is mapped, or
* {@code null} if this map contains no mapping for the key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
V get( int key );
// Modification Operations
/**
* Associates the specified value with the specified key in this map
* (optional operation). If the map previously contained a mapping for
* the key, the old value is replaced by the specified value. (A map
* <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
* if {@link #containsKey(int) m.containsKey(k)} would return
* <tt>true</tt>.)
*
* @param key key with which the specified value is to be associated
* @param value an <tt>int</tt> value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>no_entry_value</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>no_entry_value</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>,
* if the implementation supports <tt>null</tt> values.)
* @throws UnsupportedOperationException if the <tt>put</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* @throws NullPointerException if the specified key or value is null
* and this map does not permit null keys or values
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* @see #getNoEntryKey()
*/
V put( int key, V value);
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key key with which the specified value is to be associated
* @param value an <tt>int</tt> value to be associated with the specified key
*
* @return the previous value associated with <tt>key</tt>, or null
* if none was found.
*/
V putIfAbsent( int key, V value );
/**
* Removes the mapping for a key from this map if it is present
* (optional operation). More formally, if this map contains a mapping
* from key <tt>k</tt> to value <tt>v</tt> such that
* <code>key.equals(k)</code>, that mapping
* is removed. (The map can contain at most one such mapping.)
*
* <p>Returns the value to which this map previously associated the key,
* or <tt>null</tt> if the map contained no mapping for the key.
*
* <p>If this map permits null values, then a return value of
* <tt>null</tt> does not <i>necessarily</i> indicate that the map
* contained no mapping for the key; it's also possible that the map
* explicitly mapped the key to <tt>null</tt>.
*
* <p>The map will not contain a mapping for the specified key once the
* call returns.
*
* @param key key whose mapping is to be removed from the map
* @return the previous <tt>int</tt> value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this map
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this
* map does not permit null keys (optional)
*/
V remove( int key );
// Bulk Operations
/**
* Copies all of the mappings from the specified map to this map
* (optional operation). The effect of this call is equivalent to that
* of calling {@link #put(int,Object) put(k, v)} on this map once
* for each mapping from key <tt>k</tt> to value <tt>v</tt> in the
* specified map. The behavior of this operation is undefined if the
* specified map is modified while the operation is in progress.
*
* @param m mappings to be stored in this map
* @throws UnsupportedOperationException if the <tt>putAll</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of a key or value in the
* specified map prevents it from being stored in this map
* @throws NullPointerException if the specified map is null, or if
* this map does not permit null keys or values, and the
* specified map contains null keys or values
* @throws IllegalArgumentException if some property of a key or value in
* the specified map prevents it from being stored in this map
*/
void putAll( Map<? extends Integer, ? extends V> m);
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
void putAll( TIntObjectMap<? extends V> map );
/**
* Removes all of the mappings from this map (optional operation).
* The map will be empty after this call returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this map
*/
void clear();
// Views
/**
* Returns a {@link TIntSet} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*
* @return a set view of the keys contained in this map
*/
TIntSet keySet();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @return a copy of the keys of the map as an array.
*/
int[] keys();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
int[] keys( int[] array );
/**
* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own <tt>remove</tt> operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>Iterator.remove</tt>,
* <tt>Collection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a collection view of the values contained in this map
*/
Collection<V> valueCollection();
/**
* Returns the values of the map as an array of <tt>int</tt> values.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @return the values of the map as an array of <tt>int</tt> values.
*/
V[] values();
/**
* Returns the values of the map using an existing array.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>int</tt> values.
*/
V[] values( V[] array );
/**
* Returns a <tt>TIntObjectIterator</tt> with access to this map's keys and values.
*
* @return a <tt>TIntObjectIterator</tt> with access to this map's keys and values.
*/
public TIntObjectIterator<V> iterator();
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TIntProcedure procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TObjectProcedure<? super V> procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TIntObjectProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TIntObjectProcedure<? super V> procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TObjectFunction</code> value
*/
public void transformValues( TObjectFunction<V,V> function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TIntObjectProcedure<? super V> procedure );
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
boolean equals( Object o );
/**
* Returns the hash code value for this map. The hash code of a map is
* defined to be the sum of the hash codes of each entry in the map's
* <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
* implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
* <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this map
* @see Object#equals(Object)
* @see #equals(Object)
*/
int hashCode();
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.function.*;
import gnu.trove.iterator.*;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.TLongCollection;
import java.util.Map;
import java.io.Serializable;
/**
* Interface for a primitive map of int keys and long values.
*/
public interface TIntLongMap {
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null key in this collection.
*/
public int getNoEntryKey();
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
public long getNoEntryValue();
/**
* Inserts a key/value pair into the map.
*
* @param key an <code>int</code> value
* @param value an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long put( int key, long value );
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key an <code>int</code> value
* @param value an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long putIfAbsent( int key, long value );
/**
* Put all the entries from the given Map into this map.
*
* @param map The Map from which entries will be obtained to put into this map.
*/
public void putAll( Map<? extends Integer, ? extends Long> map );
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
public void putAll( TIntLongMap map );
/**
* Retrieves the value for <tt>key</tt>
*
* @param key an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long get( int key );
/**
* Empties the map.
*/
public void clear();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
public boolean isEmpty();
/**
* Deletes a key/value pair from the map.
*
* @param key an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long remove( int key );
/**
* Returns an <tt>int</tt> value that is the number of elements in the map.
*
* @return an <tt>int</tt> value that is the number of elements in the map.
*/
public int size();
/**
* Returns the keys of the map as a <tt>TIntSet</tt>
*
* @return the keys of the map as a <tt>TIntSet</tt>
*/
public TIntSet keySet();
/**
* Returns the keys of the map as an array of <tt>int</tt> values.
*
* @return the keys of the map as an array of <tt>int</tt> values.
*/
public int[] keys();
/**
* Returns the keys of the map.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
public int[] keys( int[] array );
/**
* Returns the values of the map as a <tt>TLongCollection</tt>
*
* @return the values of the map as a <tt>TLongCollection</tt>
*/
public TLongCollection valueCollection();
/**
* Returns the values of the map as an array of <tt>#e#</tt> values.
*
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public long[] values();
/**
* Returns the values of the map using an existing array.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public long[] values( long[] array );
/**
* Checks for the presence of <tt>val</tt> in the values of the map.
*
* @param val an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean containsValue( long val );
/**
* Checks for the present of <tt>key</tt> in the keys of the map.
*
* @param key an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean containsKey( int key );
/**
* @return a TIntLongIterator with access to this map's keys and values
*/
public TIntLongIterator iterator();
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TIntProcedure procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>T#F#Procedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TLongProcedure procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOIntLongProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TIntLongProcedure procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TLongFunction</code> value
*/
public void transformValues( TLongFunction function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TIntLongProcedure procedure );
/**
* Increments the primitive value mapped to key by 1
*
* @param key the key of the value to increment
* @return true if a mapping was found and modified.
*/
public boolean increment( int key );
/**
* Adjusts the primitive value mapped to key.
*
* @param key the key of the value to increment
* @param amount the amount to adjust the value by.
* @return true if a mapping was found and modified.
*/
public boolean adjustValue( int key, long amount );
/**
* Adjusts the primitive value mapped to the key if the key is present in the map.
* Otherwise, the <tt>initial_value</tt> is put in the map.
*
* @param key the key of the value to increment
* @param adjust_amount the amount to adjust the value by
* @param put_amount the value put into the map if the key is not initial present
*
* @return the value present in the map after the adjustment or put operation
*/
public long adjustOrPutValue( int key, long adjust_amount, long put_amount );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
import gnu.trove.TIntCollection;
import gnu.trove.function.TIntFunction;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.procedure.TObjectIntProcedure;
import gnu.trove.iterator.TObjectIntIterator;
import java.util.Map;
import java.util.Set;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for a primitive map of Object keys and int values.
*/
public interface TObjectIntMap<K> {
// Query Operations
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
int getNoEntryValue();
/**
* Returns the number of key-value mappings in this map. If the
* map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of key-value mappings in this map
*/
int size();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this map contains a mapping for the specified
* key. More formally, returns <tt>true</tt> if and only if
* this map contains a mapping for a key <tt>k</tt> such that
* <tt>(key==null ? k==null : key.equals(k))</tt>. (There can be
* at most one such mapping.)
*
* @param key key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
boolean containsKey( Object key );
/**
* Returns <tt>true</tt> if this map maps one or more keys to the
* specified value. More formally, returns <tt>true</tt> if and only if
* this map contains at least one mapping to a value <tt>v</tt> such that
* <tt>(value==no_entry_value ? v==no_entry_value : value.equals(v))</tt>. This operation
* will probably require time linear in the map size for most
* implementations of the <tt>Map</tt> interface.
*<p/>
* Note that no_entry_value is the result of {@link #getNoEntryValue()} and represents
* null for this map instance.
*
* @param value <tt>int</tt> value whose presence in this map is to be tested
* @return <tt>true</tt> if this map maps one or more keys to the
* specified value
* @throws ClassCastException if the value is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified value is null and this
* map does not permit null values (optional)
*/
boolean containsValue( int value );
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>If this map permits null values, then a return value of
* {@code null} does not <i>necessarily</i> indicate that the map
* contains no mapping for the key; it's also possible that the map
* explicitly maps the key to {@code null}. The {@link #containsKey
* containsKey} operation may be used to distinguish these two cases.
*
* @param key the key whose associated value is to be returned
* @return the <tt>int</tt> value to which the specified key is mapped, or
* {@code null} if this map contains no mapping for the key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
int get( Object key );
// Modification Operations
/**
* Associates the specified value with the specified key in this map
* (optional operation). If the map previously contained a mapping for
* the key, the old value is replaced by the specified value. (A map
* <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
* if {@link #containsKey(Object) m.containsKey(k)} would return
* <tt>true</tt>.)
*
* @param key key with which the specified value is to be associated
* @param value an <tt>int</tt> value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>no_entry_value</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>no_entry_value</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>,
* if the implementation supports <tt>null</tt> values.)
* @throws UnsupportedOperationException if the <tt>put</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* @throws NullPointerException if the specified key or value is null
* and this map does not permit null keys or values
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* @see #getNoEntryValue()
*/
int put( K key, int value);
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key key with which the specified value is to be associated
* @param value an <tt>int</tt> value to be associated with the specified key
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
int putIfAbsent( K key, int value );
/**
* Removes the mapping for a key from this map if it is present
* (optional operation). More formally, if this map contains a mapping
* from key <tt>k</tt> to value <tt>v</tt> such that
* <code>(key==null ? k==null : key.equals(k))</code>, that mapping
* is removed. (The map can contain at most one such mapping.)
*
* <p>Returns the value to which this map previously associated the key,
* or <tt>null</tt> if the map contained no mapping for the key.
*
* <p>If this map permits null values, then a return value of
* <tt>null</tt> does not <i>necessarily</i> indicate that the map
* contained no mapping for the key; it's also possible that the map
* explicitly mapped the key to <tt>null</tt>.
*
* <p>The map will not contain a mapping for the specified key once the
* call returns.
*
* @param key key whose mapping is to be removed from the map
* @return the previous <tt>int</tt> value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this map
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this
* map does not permit null keys (optional)
*/
int remove( Object key );
// Bulk Operations
/**
* Copies all of the mappings from the specified map to this map
* (optional operation). The effect of this call is equivalent to that
* of calling {@link #put(Object,int) put(k, v)} on this map once
* for each mapping from key <tt>k</tt> to value <tt>v</tt> in the
* specified map. The behavior of this operation is undefined if the
* specified map is modified while the operation is in progress.
*
* @param m mappings to be stored in this map
* @throws UnsupportedOperationException if the <tt>putAll</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of a key or value in the
* specified map prevents it from being stored in this map
* @throws NullPointerException if the specified map is null, or if
* this map does not permit null keys or values, and the
* specified map contains null keys or values
* @throws IllegalArgumentException if some property of a key or value in
* the specified map prevents it from being stored in this map
*/
void putAll( Map<? extends K, ? extends Integer> m);
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
void putAll( TObjectIntMap<? extends K> map );
/**
* Removes all of the mappings from this map (optional operation).
* The map will be empty after this call returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this map
*/
void clear();
// Views
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*
* @return a set view of the keys contained in this map
*/
Set<K> keySet();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @return a copy of the keys of the map as an array.
*/
Object[] keys();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
K[] keys( K[] array );
/**
* Returns a {@link TIntCollection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own <tt>remove</tt> operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>TIntIterator.remove</tt>,
* <tt>TIntCollection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a collection view of the values contained in this map
*/
TIntCollection valueCollection();
/**
* Returns the values of the map as an array of <tt>int</tt> values.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @return the values of the map as an array of <tt>int</tt> values.
*/
int[] values();
/**
* Returns the values of the map using an existing array.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>int</tt> values.
*/
int[] values( int[] array );
/**
* Returns a <tt>TObjectIntIterator</tt> with access to this map's keys and values.
*
* @return a <tt>TObjectIntIterator</tt> with access to this map's keys and values.
*/
public TObjectIntIterator<K> iterator();
/**
* Increments the primitive value mapped to key by 1
*
* @param key the key of the value to increment
* @return true if a mapping was found and modified.
*/
public boolean increment( K key );
/**
* Adjusts the primitive value mapped to key.
*
* @param key the key of the value to increment
* @param amount the amount to adjust the value by.
* @return true if a mapping was found and modified.
*/
public boolean adjustValue( K key, int amount );
/**
* Adjusts the primitive value mapped to the key if the key is present in the map.
* Otherwise, the <tt>initial_value</tt> is put in the map.
*
* @param key the key of the value to increment
* @param adjust_amount the amount to adjust the value by
* @param put_amount the value put into the map if the key is not initial present
*
* @return the value present in the map after the adjustment or put operation
*/
public int adjustOrPutValue( K key, int adjust_amount, int put_amount );
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TObjectProcedure<? super K> procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TIntProcedure procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOObjectIntProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TObjectIntProcedure<? super K> procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TIntFunction</code> value
*/
public void transformValues( TIntFunction function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TObjectIntProcedure<? super K> procedure );
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
boolean equals( Object o );
/**
* Returns the hash code value for this map. The hash code of a map is
* defined to be the sum of the hash codes of each entry in the map's
* <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
* implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
* <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this map
* @see Object#equals(Object)
* @see #equals(Object)
*/
int hashCode();
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove;
/**
* Simple class meant as a possible main class (via manifest) to report the
* implementation version of the trove4j jar.
* <p/>
* This may be useful to ask feedback WITH build version information
* <p/>
* The Main-Class entry in the manifest.mf should be set during the build as well
* as the Implementation-Version manifest attribute should be set as well.
* <p/>
* Created by IntelliJ IDEA.
* User: Johan Parent
* Date: 3/03/11
* Time: 22:10
*/
public class Version {
public static void main(String[] args) {
System.out.println(getVersion());
}
/**
* Returns the implementation version of trove4j. Intended for applications
* wanting to return the version of trove4j they are using
* <p/>
* NOTE: this method will only return a useful version when working
* with a trove4j jar as it requires a manifest file
*
* @return
*/
public static String getVersion() {
String version = Version.class.getPackage().getImplementationVersion();
//
if (version != null) {
return "trove4j version " + version;
}
return "Sorry no Implementation-Version manifest attribute available";
}
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.queue;
import gnu.trove.TLongCollection;
import java.io.Serializable;
/**
* Interface for Trove queue implementations.
*
* @see java.util.Queue
*/
public interface TLongQueue extends TLongCollection {
/**
* Retrieves and removes the head of this queue. This method differs from
* {@link #poll} only in that it throws an exception if this queue is empty.
*/
public long element();
/**
* Inserts the specified element into this queue if it is possible to do so
* immediately without violating capacity restrictions. When using a
* capacity-restricted queue, this method is generally preferable to
* {@link #add}, which can fail to insert an element only by throwing an exception.
*
* @param e The element to add.
*
* @return <tt>true</tt> if the element was added to this queue, else <tt>false</tt>
*/
public boolean offer( long e );
/**
* Retrieves, but does not remove, the head of this queue, or returns
* {@link #getNoEntryValue} if this queue is empty.
*
* @return the head of this queue, or {@link #getNoEntryValue} if this queue is empty
*/
public long peek();
/**
* Retrieves and removes the head of this queue, or returns {@link #getNoEntryValue}
* if this queue is empty.
*
* @return the head of this queue, or {@link #getNoEntryValue} if this queue is empty
*/
public long poll();
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.queue;
import gnu.trove.TIntCollection;
import java.io.Serializable;
/**
* Interface for Trove queue implementations.
*
* @see java.util.Queue
*/
public interface TIntQueue extends TIntCollection {
/**
* Retrieves and removes the head of this queue. This method differs from
* {@link #poll} only in that it throws an exception if this queue is empty.
*/
public int element();
/**
* Inserts the specified element into this queue if it is possible to do so
* immediately without violating capacity restrictions. When using a
* capacity-restricted queue, this method is generally preferable to
* {@link #add}, which can fail to insert an element only by throwing an exception.
*
* @param e The element to add.
*
* @return <tt>true</tt> if the element was added to this queue, else <tt>false</tt>
*/
public boolean offer( int e );
/**
* Retrieves, but does not remove, the head of this queue, or returns
* {@link #getNoEntryValue} if this queue is empty.
*
* @return the head of this queue, or {@link #getNoEntryValue} if this queue is empty
*/
public int peek();
/**
* Retrieves and removes the head of this queue, or returns {@link #getNoEntryValue}
* if this queue is empty.
*
* @return the head of this queue, or {@link #getNoEntryValue} if this queue is empty
*/
public int poll();
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.stack;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import java.io.Serializable;
/**
* A stack of long primitives.
*/
public interface TLongStack {
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryValue();
/**
* Pushes the value onto the top of the stack.
*
* @param val an <code>long</code> value
*/
public void push( long val );
/**
* Removes and returns the value at the top of the stack.
*
* @return an <code>long</code> value
*/
public long pop();
/**
* Returns the value at the top of the stack.
*
* @return an <code>long</code> value
*/
public long peek();
/**
* Returns the current depth of the stack.
*/
public int size();
/**
* Clears the stack.
*/
public void clear();
/**
* Copies the contents of the stack into a native array. Note that this will NOT
* pop them out of the stack.
*
* @return an <code>long[]</code> value
*/
public long[] toArray();
/**
* Copies a slice of the list into a native array. Note that this will NOT
* pop them out of the stack.
*
* @param dest the array to copy into.
*/
public void toArray( long[] dest );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.stack;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import java.io.Serializable;
/**
* A stack of int primitives.
*/
public interface TIntStack {
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryValue();
/**
* Pushes the value onto the top of the stack.
*
* @param val an <code>int</code> value
*/
public void push( int val );
/**
* Removes and returns the value at the top of the stack.
*
* @return an <code>int</code> value
*/
public int pop();
/**
* Returns the value at the top of the stack.
*
* @return an <code>int</code> value
*/
public int peek();
/**
* Returns the current depth of the stack.
*/
public int size();
/**
* Clears the stack.
*/
public void clear();
/**
* Copies the contents of the stack into a native array. Note that this will NOT
* pop them out of the stack.
*
* @return an <code>int[]</code> value
*/
public int[] toArray();
/**
* Copies a slice of the list into a native array. Note that this will NOT
* pop them out of the stack.
*
* @param dest the array to copy into.
*/
public void toArray( int[] dest );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.stack.array;
import gnu.trove.stack.TIntStack;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.impl.*;
import java.io.Externalizable;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.IOException;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* A stack of int primitives, backed by a TIntArrayList
*/
public class TIntArrayStack implements TIntStack, Externalizable {
static final long serialVersionUID = 1L;
/** the list used to hold the stack values. */
protected TIntArrayList _list;
public static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY;
/**
* Creates a new <code>TIntArrayStack</code> instance with the default
* capacity.
*/
public TIntArrayStack() {
this( DEFAULT_CAPACITY );
}
/**
* Creates a new <code>TIntArrayStack</code> instance with the
* specified capacity.
*
* @param capacity the initial depth of the stack
*/
public TIntArrayStack( int capacity ) {
_list = new TIntArrayList( capacity );
}
/**
* Creates a new <code>TIntArrayStack</code> instance with the
* specified capacity.
*
* @param capacity the initial depth of the stack
* @param no_entry_value value that represents null
*/
public TIntArrayStack( int capacity, int no_entry_value ) {
_list = new TIntArrayList( capacity, no_entry_value );
}
/**
* Creates a new <code>TIntArrayStack</code> instance that is
* a copy of the instanced passed to us.
*
* @param stack the instance to copy
*/
public TIntArrayStack( TIntStack stack ) {
if ( stack instanceof TIntArrayStack ) {
TIntArrayStack array_stack = ( TIntArrayStack ) stack;
this._list = new TIntArrayList( array_stack._list );
} else {
throw new UnsupportedOperationException( "Only support TIntArrayStack" );
}
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryValue() {
return _list.getNoEntryValue();
}
/**
* Pushes the value onto the top of the stack.
*
* @param val an <code>int</code> value
*/
public void push( int val ) {
_list.add( val );
}
/**
* Removes and returns the value at the top of the stack.
*
* @return an <code>int</code> value
*/
public int pop() {
return _list.removeAt( _list.size() - 1 );
}
/**
* Returns the value at the top of the stack.
*
* @return an <code>int</code> value
*/
public int peek() {
return _list.get( _list.size() - 1 );
}
/**
* Returns the current depth of the stack.
*/
public int size() {
return _list.size();
}
/**
* Clears the stack.
*/
public void clear() {
_list.clear();
}
/**
* Copies the contents of the stack into a native array. Note that this will NOT
* pop them out of the stack. The front of the list will be the top of the stack.
*
* @return an <code>int[]</code> value
*/
public int[] toArray() {
int[] retval = _list.toArray();
reverse( retval, 0, size() );
return retval;
}
/**
* Copies a slice of the list into a native array. Note that this will NOT
* pop them out of the stack. The front of the list will be the top
* of the stack.
* <p>
* If the native array is smaller than the stack depth,
* the native array will be filled with the elements from the top
* of the array until it is full and exclude the remainder.
*
* @param dest the array to copy into.
*/
public void toArray( int[] dest ) {
int size = size();
int start = size - dest.length;
if ( start < 0 ) {
start = 0;
}
int length = Math.min( size, dest.length );
_list.toArray( dest, start, length );
reverse( dest, 0, length );
if ( dest.length > size ) {
dest[size] = _list.getNoEntryValue();
}
}
/**
* Reverse the order of the elements in the range of the list.
*
* @param dest the array of data
* @param from the inclusive index at which to start reversing
* @param to the exclusive index at which to stop reversing
*/
private void reverse( int[] dest, int from, int to ) {
if ( from == to ) {
return; // nothing to do
}
if ( from > to ) {
throw new IllegalArgumentException( "from cannot be greater than to" );
}
for ( int i = from, j = to - 1; i < j; i++, j-- ) {
swap( dest, i, j );
}
}
/**
* Swap the values at offsets <tt>i</tt> and <tt>j</tt>.
*
* @param dest the array of data
* @param i an offset into the data array
* @param j an offset into the data array
*/
private void swap( int[] dest, int i, int j ) {
int tmp = dest[ i ];
dest[ i ] = dest[ j ];
dest[ j ] = tmp;
}
/**
* Returns a String representation of the list, top to bottom.
*
* @return a <code>String</code> value
*/
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
for ( int i = _list.size() - 1; i > 0; i-- ) {
buf.append( _list.get( i ) );
buf.append( ", " );
}
if ( size() > 0 ) {
buf.append( _list.get( 0 ) );
}
buf.append( "}" );
return buf.toString();
}
public boolean equals( Object o ) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
TIntArrayStack that = ( TIntArrayStack ) o;
return _list.equals( that._list );
}
public int hashCode() {
return _list.hashCode();
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// LIST
out.writeObject( _list );
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// LIST
_list = ( TIntArrayList ) in.readObject();
}
} // TIntArrayStack
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.stack.array;
import gnu.trove.stack.TLongStack;
import gnu.trove.list.array.TLongArrayList;
import gnu.trove.impl.*;
import java.io.Externalizable;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.IOException;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* A stack of long primitives, backed by a TLongArrayList
*/
public class TLongArrayStack implements TLongStack, Externalizable {
static final long serialVersionUID = 1L;
/** the list used to hold the stack values. */
protected TLongArrayList _list;
public static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY;
/**
* Creates a new <code>TLongArrayStack</code> instance with the default
* capacity.
*/
public TLongArrayStack() {
this( DEFAULT_CAPACITY );
}
/**
* Creates a new <code>TLongArrayStack</code> instance with the
* specified capacity.
*
* @param capacity the initial depth of the stack
*/
public TLongArrayStack( int capacity ) {
_list = new TLongArrayList( capacity );
}
/**
* Creates a new <code>TLongArrayStack</code> instance with the
* specified capacity.
*
* @param capacity the initial depth of the stack
* @param no_entry_value value that represents null
*/
public TLongArrayStack( int capacity, long no_entry_value ) {
_list = new TLongArrayList( capacity, no_entry_value );
}
/**
* Creates a new <code>TLongArrayStack</code> instance that is
* a copy of the instanced passed to us.
*
* @param stack the instance to copy
*/
public TLongArrayStack( TLongStack stack ) {
if ( stack instanceof TLongArrayStack ) {
TLongArrayStack array_stack = ( TLongArrayStack ) stack;
this._list = new TLongArrayList( array_stack._list );
} else {
throw new UnsupportedOperationException( "Only support TLongArrayStack" );
}
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryValue() {
return _list.getNoEntryValue();
}
/**
* Pushes the value onto the top of the stack.
*
* @param val an <code>long</code> value
*/
public void push( long val ) {
_list.add( val );
}
/**
* Removes and returns the value at the top of the stack.
*
* @return an <code>long</code> value
*/
public long pop() {
return _list.removeAt( _list.size() - 1 );
}
/**
* Returns the value at the top of the stack.
*
* @return an <code>long</code> value
*/
public long peek() {
return _list.get( _list.size() - 1 );
}
/**
* Returns the current depth of the stack.
*/
public int size() {
return _list.size();
}
/**
* Clears the stack.
*/
public void clear() {
_list.clear();
}
/**
* Copies the contents of the stack into a native array. Note that this will NOT
* pop them out of the stack. The front of the list will be the top of the stack.
*
* @return an <code>long[]</code> value
*/
public long[] toArray() {
long[] retval = _list.toArray();
reverse( retval, 0, size() );
return retval;
}
/**
* Copies a slice of the list into a native array. Note that this will NOT
* pop them out of the stack. The front of the list will be the top
* of the stack.
* <p>
* If the native array is smaller than the stack depth,
* the native array will be filled with the elements from the top
* of the array until it is full and exclude the remainder.
*
* @param dest the array to copy into.
*/
public void toArray( long[] dest ) {
int size = size();
int start = size - dest.length;
if ( start < 0 ) {
start = 0;
}
int length = Math.min( size, dest.length );
_list.toArray( dest, start, length );
reverse( dest, 0, length );
if ( dest.length > size ) {
dest[size] = _list.getNoEntryValue();
}
}
/**
* Reverse the order of the elements in the range of the list.
*
* @param dest the array of data
* @param from the inclusive index at which to start reversing
* @param to the exclusive index at which to stop reversing
*/
private void reverse( long[] dest, int from, int to ) {
if ( from == to ) {
return; // nothing to do
}
if ( from > to ) {
throw new IllegalArgumentException( "from cannot be greater than to" );
}
for ( int i = from, j = to - 1; i < j; i++, j-- ) {
swap( dest, i, j );
}
}
/**
* Swap the values at offsets <tt>i</tt> and <tt>j</tt>.
*
* @param dest the array of data
* @param i an offset into the data array
* @param j an offset into the data array
*/
private void swap( long[] dest, int i, int j ) {
long tmp = dest[ i ];
dest[ i ] = dest[ j ];
dest[ j ] = tmp;
}
/**
* Returns a String representation of the list, top to bottom.
*
* @return a <code>String</code> value
*/
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
for ( int i = _list.size() - 1; i > 0; i-- ) {
buf.append( _list.get( i ) );
buf.append( ", " );
}
if ( size() > 0 ) {
buf.append( _list.get( 0 ) );
}
buf.append( "}" );
return buf.toString();
}
public boolean equals( Object o ) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
TLongArrayStack that = ( TLongArrayStack ) o;
return _list.equals( that._list );
}
public int hashCode() {
return _list.hashCode();
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// LIST
out.writeObject( _list );
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// LIST
_list = ( TLongArrayList ) in.readObject();
}
} // TLongArrayStack
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2002, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.strategy;
import java.io.Serializable;
/**
* Interface to support pluggable hashing strategies in maps and sets.
* Implementers can use this interface to make the trove hashing
* algorithms use object values, values provided by the java runtime,
* or a custom strategy when computing hashcodes.
*
* @author Eric Friedman
* @author Rob Eden
*/
public interface HashingStrategy<T> extends Serializable {
static final long serialVersionUID = 5674097166776615540L;
/**
* Computes a hash code for the specified object. Implementers
* can use the object's own <tt>hashCode</tt> method, the Java
* runtime's <tt>identityHashCode</tt>, or a custom scheme.
*
* @param object for which the hashcode is to be computed
* @return the hashCode
*/
int computeHashCode( T object );
/**
* Compares o1 and o2 for equality. Strategy implementers may use
* the objects' own equals() methods, compare object references,
* or implement some custom scheme.
*
* @param o1 an <code>Object</code> value
* @param o2 an <code>Object</code> value
* @return true if the objects are equal according to this strategy.
*/
boolean equals( T o1, T o2 );
}
| Java |
package gnu.trove.strategy;
/**
* A {@link gnu.trove.strategy.HashingStrategy} that does identity comparisons
* (<tt>==</tt>) and uses {@link System#identityHashCode(Object)} for hashCode generation.
*/
public class IdentityHashingStrategy<K> implements HashingStrategy<K> {
static final long serialVersionUID = -5188534454583764904L;
public int computeHashCode( K object ) {
return System.identityHashCode( object );
}
public boolean equals( K o1, K o2 ) {
return o1 == o2;
}
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type long and long.
*/
public interface TLongLongProcedure {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a a <code>long</code> value
* @param b a <code>long</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( long a, long b );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type long and int.
*/
public interface TLongIntProcedure {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a a <code>long</code> value
* @param b a <code>int</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( long a, int b );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type int and long.
*/
public interface TIntLongProcedure {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a a <code>int</code> value
* @param b a <code>long</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( int a, long b );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
/**
* Interface for procedures that take two Object parameters.
* <p/>
* Created: Mon Nov 5 22:03:30 2001
*
* @author Eric D. Friedman
* @version $Id: TObjectObjectProcedure.java,v 1.1.2.1 2009/09/06 17:02:20 upholderoftruth Exp $
*/
public interface TObjectObjectProcedure<K, V> {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a an <code>Object</code> value
* @param b an <code>Object</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( K a, V b );
}// TObjectObjectProcedure
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures with one int parameter.
*/
public interface TIntProcedure {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param value a value of type <code>int</code>
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( int value );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type Object and int.
*/
public interface TObjectIntProcedure<K> {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a an <code>Object</code> value
* @param b a <code>int</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( K a, int b );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
/**
* Interface for procedures with one Object parameter.
*
* Created: Mon Nov 5 21:45:49 2001
*
* @author Eric D. Friedman
* @version $Id: TObjectProcedure.java,v 1.1.2.1 2009/09/02 21:52:33 upholderoftruth Exp $
*/
public interface TObjectProcedure<T> {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param object an <code>Object</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute(T object);
}// TObjectProcedure
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type int and Object.
*/
public interface TIntObjectProcedure<T> {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a a <code>int</code> value
* @param b an <code>Object</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( int a, T b );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type long and Object.
*/
public interface TLongObjectProcedure<T> {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a a <code>long</code> value
* @param b an <code>Object</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( long a, T b );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure.array;
import gnu.trove.procedure.TObjectProcedure;
/**
* A procedure which stores each value it receives into a target array.
* <p/>
* Created: Sat Jan 12 10:13:42 2002
*
* @author Eric D. Friedman
* @version $Id: ToObjectArrayProceedure.java,v 1.1.2.1 2009/09/02 21:52:33 upholderoftruth Exp $
*/
public final class ToObjectArrayProceedure<T> implements TObjectProcedure<T> {
private final T[] target;
private int pos = 0;
public ToObjectArrayProceedure( final T[] target ) {
this.target = target;
}
public final boolean execute( T value ) {
target[pos++] = value;
return true;
}
} // ToObjectArrayProcedure | Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type int and int.
*/
public interface TIntIntProcedure {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a a <code>int</code> value
* @param b a <code>int</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( int a, int b );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type Object and long.
*/
public interface TObjectLongProcedure<K> {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a an <code>Object</code> value
* @param b a <code>long</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( K a, long b );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures with one long parameter.
*/
public interface TLongProcedure {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param value a value of type <code>long</code>
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( long value );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
// Copyright (c) 2011, Johan Parent All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list.linked;
import gnu.trove.function.TIntFunction;
import gnu.trove.list.TIntList;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.TIntCollection;
import gnu.trove.impl.*;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* A resizable, double linked list of int primitives.
*/
public class TIntLinkedList implements TIntList, Externalizable {
int no_entry_value;
int size;
TIntLink head = null;
TIntLink tail = head;
public TIntLinkedList() {
}
public TIntLinkedList(int no_entry_value) {
this.no_entry_value = no_entry_value;
}
public TIntLinkedList(TIntList list) {
no_entry_value = list.getNoEntryValue();
//
for (TIntIterator iterator = list.iterator(); iterator.hasNext();) {
int next = iterator.next();
add(next);
}
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return size() == 0;
}
/** {@inheritDoc} */
public boolean add(int val) {
TIntLink l = new TIntLink(val);
if (no(head)) {
head = l;
tail = l;
} else {
l.setPrevious(tail);
tail.setNext(l);
//
tail = l;
}
size++;
return true;
}
/** {@inheritDoc} */
public void add(int[] vals) {
for (int val : vals) {
add(val);
}
}
/** {@inheritDoc} */
public void add(int[] vals, int offset, int length) {
for (int i = 0; i < length; i++) {
int val = vals[offset + i];
add(val);
}
}
/** {@inheritDoc} */
public void insert(int offset, int value) {
TIntLinkedList tmp = new TIntLinkedList();
tmp.add(value);
insert(offset, tmp);
}
/** {@inheritDoc} */
public void insert(int offset, int[] values) {
insert(offset, link(values, 0, values.length));
}
/** {@inheritDoc} */
public void insert(int offset, int[] values, int valOffset, int len) {
insert(offset, link(values, valOffset, len));
}
void insert(int offset, TIntLinkedList tmp) {
TIntLink l = getLinkAt(offset);
size = size + tmp.size;
//
if (l == head) {
// Add in front
tmp.tail.setNext(head);
head.setPrevious(tmp.tail);
head = tmp.head;
return;
}
if (no(l)) {
if (size == 0) {
// New empty list
head = tmp.head;
tail = tmp.tail;
} else {
// append
tail.setNext(tmp.head);
tmp.head.setPrevious(tail);
tail = tmp.tail;
}
} else {
TIntLink prev = l.getPrevious();
l.getPrevious().setNext(tmp.head);
// Link by behind tmp
tmp.tail.setNext(l);
l.setPrevious(tmp.tail);
tmp.head.setPrevious(prev);
}
}
static TIntLinkedList link(int[] values, int valOffset, int len) {
TIntLinkedList ret = new TIntLinkedList();
for (int i = 0; i < len; i++) {
ret.add(values[valOffset + i]);
}
return ret;
}
/** {@inheritDoc} */
public int get(int offset) {
if (offset > size)
throw new IndexOutOfBoundsException("index " + offset + " exceeds size " + size);
TIntLink l = getLinkAt(offset);
//
if (no(l))
return no_entry_value;
return l.getValue();
}
/**
* Returns the link at the given offset.
* <p/>
* A simple bisection criteria is used to keep the worst case complexity equal to
* O(n/2) where n = size(). Simply start from head of list or tail depending on offset
* and list size.
*
* @param offset of the link
* @return link or null if non-existent
*/
public TIntLink getLinkAt(int offset) {
if (offset >= size())
return null;
if (offset <= (size() >>> 1))
return getLink(head, 0, offset, true);
else
return getLink(tail, size() - 1, offset, false);
}
/**
* Returns the link at absolute offset starting from given the initial link 'l' at index 'idx'
*
* @param l
* @param idx
* @param offset
* @return
*/
private static TIntLink getLink(TIntLink l, int idx, int offset) {
return getLink(l, idx, offset, true);
}
/**
* Returns link at given absolute offset starting from link 'l' at index 'idx'
* @param l
* @param idx
* @param offset
* @param next
* @return
*/
private static TIntLink getLink(TIntLink l, int idx, int offset, boolean next) {
int i = idx;
//
while (got(l)) {
if (i == offset) {
return l;
}
i = i + (next ? 1 : -1);
l = next ? l.getNext() : l.getPrevious();
}
return null;
}
/** {@inheritDoc} */
public int set(int offset, int val) {
if (offset > size)
throw new IndexOutOfBoundsException("index " + offset + " exceeds size " + size);
TIntLink l = getLinkAt(offset);
//
if (no(l))
throw new IndexOutOfBoundsException("at offset " + offset);
int prev = l.getValue();
l.setValue(val);
return prev;
}
/** {@inheritDoc} */
public void set(int offset, int[] values) {
set(offset, values, 0, values.length);
}
/** {@inheritDoc} */
public void set(int offset, int[] values, int valOffset, int length) {
for (int i = 0; i < length; i++) {
int value = values[valOffset + i];
set(offset + i, value);
}
}
/** {@inheritDoc} */
public int replace(int offset, int val) {
return set(offset, val);
}
/** {@inheritDoc} */
public void clear() {
size = 0;
//
head = null;
tail = null;
}
/** {@inheritDoc} */
public boolean remove(int value) {
boolean changed = false;
for (TIntLink l = head; got(l); l = l.getNext()) {
//
if (l.getValue() == value) {
changed = true;
//
removeLink(l);
}
}
return changed;
}
/**
* unlinks the give TIntLink from the list
*
* @param l
*/
private void removeLink(TIntLink l) {
if (no(l))
return;
size--;
TIntLink prev = l.getPrevious();
TIntLink next = l.getNext();
if (got(prev)) {
prev.setNext(next);
} else {
// No previous we must be head
head = next;
}
if (got(next)) {
next.setPrevious(prev);
} else {
// No next so me must be tail
tail = prev;
}
// Unlink
l.setNext(null);
l.setPrevious(null);
}
/** {@inheritDoc} */
public boolean containsAll(Collection<?> collection) {
if (isEmpty())
return false;
for (Object o : collection) {
if (o instanceof Integer) {
Integer i = (Integer) o;
if (!(contains(i)))
return false;
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll(TIntCollection collection) {
if (isEmpty())
return false;
for (TIntIterator it = collection.iterator(); it.hasNext();) {
int i = it.next();
if (!(contains(i)))
return false;
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll(int[] array) {
if (isEmpty())
return false;
for (int i : array) {
if (!contains(i))
return false;
}
return true;
}
/** {@inheritDoc} */
public boolean addAll(Collection<? extends Integer> collection) {
boolean ret = false;
for (Integer v : collection) {
if (add(v.intValue()))
ret = true;
}
return ret;
}
/** {@inheritDoc} */
public boolean addAll(TIntCollection collection) {
boolean ret = false;
for (TIntIterator it = collection.iterator(); it.hasNext();) {
int i = it.next();
if (add(i))
ret = true;
}
return ret;
}
/** {@inheritDoc} */
public boolean addAll(int[] array) {
boolean ret = false;
for (int i : array) {
if (add(i))
ret = true;
}
return ret;
}
/** {@inheritDoc} */
public boolean retainAll(Collection<?> collection) {
boolean modified = false;
TIntIterator iter = iterator();
while (iter.hasNext()) {
if (!collection.contains(Integer.valueOf(iter.next()))) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll(TIntCollection collection) {
boolean modified = false;
TIntIterator iter = iterator();
while (iter.hasNext()) {
if (!collection.contains(iter.next())) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll(int[] array) {
Arrays.sort(array);
boolean modified = false;
TIntIterator iter = iterator();
while (iter.hasNext()) {
if (Arrays.binarySearch(array, iter.next()) < 0) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean removeAll(Collection<?> collection) {
boolean modified = false;
TIntIterator iter = iterator();
while (iter.hasNext()) {
if (collection.contains(Integer.valueOf(iter.next()))) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean removeAll(TIntCollection collection) {
boolean modified = false;
TIntIterator iter = iterator();
while (iter.hasNext()) {
if (collection.contains(iter.next())) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean removeAll(int[] array) {
Arrays.sort(array);
boolean modified = false;
TIntIterator iter = iterator();
while (iter.hasNext()) {
if (Arrays.binarySearch(array, iter.next()) >= 0) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public int removeAt(int offset) {
TIntLink l = getLinkAt(offset);
if (no(l))
throw new ArrayIndexOutOfBoundsException("no elemenet at " + offset);
int prev = l.getValue();
removeLink(l);
return prev;
}
/** {@inheritDoc} */
public void remove(int offset, int length) {
for (int i = 0; i < length; i++) {
removeAt(offset); // since the list shrinks we don't need to use offset+i to get the next entry ;)
}
}
/** {@inheritDoc} */
public void transformValues(TIntFunction function) {
for (TIntLink l = head; got(l);) {
//
l.setValue(function.execute(l.getValue()));
//
l = l.getNext();
}
}
/** {@inheritDoc} */
public void reverse() {
TIntLink h = head;
TIntLink t = tail;
TIntLink prev, next, tmp;
//
TIntLink l = head;
while (got(l)) {
next = l.getNext();
prev = l.getPrevious();
//
tmp = l;
l = l.getNext();
//
tmp.setNext(prev);
tmp.setPrevious(next);
}
//
head = t;
tail = h;
}
/** {@inheritDoc} */
public void reverse(int from, int to) {
if (from > to)
throw new IllegalArgumentException("from > to : " + from + ">" + to);
TIntLink start = getLinkAt(from);
TIntLink stop = getLinkAt(to);
TIntLink prev, next;
TIntLink tmp = null;
TIntLink tmpHead = start.getPrevious();
//
TIntLink l = start;
while (l != stop) {
next = l.getNext();
prev = l.getPrevious();
//
tmp = l;
l = l.getNext();
//
tmp.setNext(prev);
tmp.setPrevious(next);
}
// At this point l == stop and tmp is the but last element {
if (got(tmp)) {
tmpHead.setNext(tmp);
stop.setPrevious(tmpHead);
}
start.setNext(stop);
stop.setPrevious(start);
}
/** {@inheritDoc} */
public void shuffle(Random rand) {
for (int i = 0; i < size; i++) {
TIntLink l = getLinkAt(rand.nextInt(size()));
removeLink(l);
add(l.getValue());
}
}
/** {@inheritDoc} */
public TIntList subList(int begin, int end) {
if (end < begin) {
throw new IllegalArgumentException("begin index " + begin +
" greater than end index " + end);
}
if (size < begin) {
throw new IllegalArgumentException("begin index " + begin +
" greater than last index " + size);
}
if (begin < 0) {
throw new IndexOutOfBoundsException("begin index can not be < 0");
}
if (end > size) {
throw new IndexOutOfBoundsException("end index < " + size);
}
TIntLinkedList ret = new TIntLinkedList();
TIntLink tmp = getLinkAt(begin);
for (int i = begin; i < end; i++) {
ret.add(tmp.getValue()); // copy
tmp = tmp.getNext();
}
return ret;
}
/** {@inheritDoc} */
public int[] toArray() {
return toArray(new int[size], 0, size);
}
/** {@inheritDoc} */
public int[] toArray(int offset, int len) {
return toArray(new int[len], offset, 0, len);
}
/** {@inheritDoc} */
public int[] toArray(int[] dest) {
return toArray(dest, 0, size);
}
/** {@inheritDoc} */
public int[] toArray(int[] dest, int offset, int len) {
return toArray(dest, offset, 0, len);
}
/** {@inheritDoc} */
public int[] toArray(int[] dest, int source_pos, int dest_pos, int len) {
if (len == 0) {
return dest; // nothing to copy
}
if (source_pos < 0 || source_pos >= size()) {
throw new ArrayIndexOutOfBoundsException(source_pos);
}
TIntLink tmp = getLinkAt(source_pos);
for (int i = 0; i < len; i++) {
dest[dest_pos + i] = tmp.getValue(); // copy
tmp = tmp.getNext();
}
return dest;
}
/** {@inheritDoc} */
public boolean forEach(TIntProcedure procedure) {
for (TIntLink l = head; got(l); l = l.getNext()) {
if (!procedure.execute(l.getValue()))
return false;
}
return true;
}
/** {@inheritDoc} */
public boolean forEachDescending(TIntProcedure procedure) {
for (TIntLink l = tail; got(l); l = l.getPrevious()) {
if (!procedure.execute(l.getValue()))
return false;
}
return true;
}
/** {@inheritDoc} */
public void sort() {
sort(0, size);
}
/** {@inheritDoc} */
public void sort(int fromIndex, int toIndex) {
TIntList tmp = subList(fromIndex, toIndex);
int[] vals = tmp.toArray();
Arrays.sort(vals);
set(fromIndex, vals);
}
/** {@inheritDoc} */
public void fill(int val) {
fill(0, size, val);
}
/** {@inheritDoc} */
public void fill(int fromIndex, int toIndex, int val) {
if (fromIndex < 0) {
throw new IndexOutOfBoundsException("begin index can not be < 0");
}
TIntLink l = getLinkAt(fromIndex);
if (toIndex > size) {
for (int i = fromIndex; i < size; i++) {
l.setValue(val);
l = l.getNext();
}
for (int i = size; i < toIndex; i++) {
add(val);
}
} else {
for (int i = fromIndex; i < toIndex; i++) {
l.setValue(val);
l = l.getNext();
}
}
}
/** {@inheritDoc} */
public int binarySearch(int value) {
return binarySearch(value, 0, size());
}
/** {@inheritDoc} */
public int binarySearch(int value, int fromIndex, int toIndex) {
if (fromIndex < 0) {
throw new IndexOutOfBoundsException("begin index can not be < 0");
}
if (toIndex > size) {
throw new IndexOutOfBoundsException("end index > size: " + toIndex + " > " + size);
}
if (toIndex < fromIndex) {
return -(fromIndex+1);
}
TIntLink middle;
int mid;
int from = fromIndex;
TIntLink fromLink = getLinkAt(fromIndex);
int to = toIndex;
while (from < to) {
mid = (from + to) >>> 1;
middle = getLink(fromLink, from, mid);
if (middle.getValue() == value)
return mid;
if (middle.getValue() < value) {
from = mid + 1;
fromLink = middle.next;
} else {
to = mid - 1;
}
}
return -(from + 1);
}
/** {@inheritDoc} */
public int indexOf(int value) {
return indexOf(0, value);
}
/** {@inheritDoc} */
public int indexOf(int offset, int value) {
int count = offset;
for (TIntLink l = getLinkAt(offset); got(l.getNext()); l = l.getNext()) {
if (l.getValue() == value)
return count;
count++;
}
return -1;
}
/** {@inheritDoc} */
public int lastIndexOf(int value) {
return lastIndexOf(0, value);
}
/** {@inheritDoc} */
public int lastIndexOf(int offset, int value) {
if (isEmpty())
return -1;
int last = -1;
int count = offset;
for (TIntLink l = getLinkAt(offset); got(l.getNext()); l = l.getNext()) {
if (l.getValue() == value)
last = count;
count++;
}
return last;
}
/** {@inheritDoc} */
public boolean contains(int value) {
if (isEmpty())
return false;
for (TIntLink l = head; got(l); l = l.getNext()) {
if (l.getValue() == value)
return true;
}
return false;
}
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntIterator() {
TIntLink l = head;
TIntLink current;
public int next() {
if (no(l))
throw new NoSuchElementException();
int ret = l.getValue();
current = l;
l = l.getNext();
return ret;
}
public boolean hasNext() {
return got(l);
}
public void remove() {
if (current == null)
throw new IllegalStateException();
removeLink(current);
current = null;
}
};
}
/** {@inheritDoc} */
public TIntList grep(TIntProcedure condition) {
TIntList ret = new TIntLinkedList();
for (TIntLink l = head; got(l); l = l.getNext()) {
if (condition.execute(l.getValue()))
ret.add(l.getValue());
}
return ret;
}
/** {@inheritDoc} */
public TIntList inverseGrep(TIntProcedure condition) {
TIntList ret = new TIntLinkedList();
for (TIntLink l = head; got(l); l = l.getNext()) {
if (!condition.execute(l.getValue()))
ret.add(l.getValue());
}
return ret;
}
/** {@inheritDoc} */
public int max() {
int ret = Integer.MIN_VALUE;
if (isEmpty())
throw new IllegalStateException();
for (TIntLink l = head; got(l); l = l.getNext()) {
if (ret < l.getValue())
ret = l.getValue();
}
return ret;
}
/** {@inheritDoc} */
public int min() {
int ret = Integer.MAX_VALUE;
if (isEmpty())
throw new IllegalStateException();
for (TIntLink l = head; got(l); l = l.getNext()) {
if (ret > l.getValue())
ret = l.getValue();
}
return ret;
}
/** {@inheritDoc} */
public int sum() {
int sum = 0;
for (TIntLink l = head; got(l); l = l.getNext()) {
sum += l.getValue();
}
return sum;
}
//
//
//
static class TIntLink {
int value;
TIntLink previous;
TIntLink next;
TIntLink(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public TIntLink getPrevious() {
return previous;
}
public void setPrevious(TIntLink previous) {
this.previous = previous;
}
public TIntLink getNext() {
return next;
}
public void setNext(TIntLink next) {
this.next = next;
}
}
class RemoveProcedure implements TIntProcedure {
boolean changed = false;
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param value a value of type <code>int</code>
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute(int value) {
if (remove(value))
changed = true;
return true;
}
public boolean isChanged() {
return changed;
}
}
/** {@inheritDoc} */
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte(0);
// NO_ENTRY_VALUE
out.writeInt(no_entry_value);
// ENTRIES
out.writeInt(size);
for (TIntIterator iterator = iterator(); iterator.hasNext();) {
int next = iterator.next();
out.writeInt(next);
}
}
/** {@inheritDoc} */
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// NO_ENTRY_VALUE
no_entry_value = in.readInt();
// ENTRIES
int len = in.readInt();
for (int i = 0; i < len; i++) {
add(in.readInt());
}
}
static boolean got(Object ref) {
return ref != null;
}
static boolean no(Object ref) {
return ref == null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TIntLinkedList that = (TIntLinkedList) o;
if (no_entry_value != that.no_entry_value) return false;
if (size != that.size) return false;
TIntIterator iterator = iterator();
TIntIterator thatIterator = that.iterator();
while (iterator.hasNext()) {
if (!thatIterator.hasNext())
return false;
if (iterator.next() != thatIterator.next())
return false;
}
return true;
}
@Override
public int hashCode() {
int result = HashFunctions.hash(no_entry_value);
result = 31 * result + size;
for (TIntIterator iterator = iterator(); iterator.hasNext();) {
result = 31 * result + HashFunctions.hash(iterator.next());
}
return result;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder("{");
TIntIterator it = iterator();
while (it.hasNext()) {
int next = it.next();
buf.append(next);
if (it.hasNext())
buf.append(", ");
}
buf.append("}");
return buf.toString();
}
} // TIntLinkedList
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
// Copyright (c) 2011, Johan Parent All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list.linked;
import gnu.trove.function.TLongFunction;
import gnu.trove.list.TLongList;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.iterator.TLongIterator;
import gnu.trove.TLongCollection;
import gnu.trove.impl.*;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* A resizable, double linked list of long primitives.
*/
public class TLongLinkedList implements TLongList, Externalizable {
long no_entry_value;
int size;
TLongLink head = null;
TLongLink tail = head;
public TLongLinkedList() {
}
public TLongLinkedList(long no_entry_value) {
this.no_entry_value = no_entry_value;
}
public TLongLinkedList(TLongList list) {
no_entry_value = list.getNoEntryValue();
//
for (TLongIterator iterator = list.iterator(); iterator.hasNext();) {
long next = iterator.next();
add(next);
}
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return size() == 0;
}
/** {@inheritDoc} */
public boolean add(long val) {
TLongLink l = new TLongLink(val);
if (no(head)) {
head = l;
tail = l;
} else {
l.setPrevious(tail);
tail.setNext(l);
//
tail = l;
}
size++;
return true;
}
/** {@inheritDoc} */
public void add(long[] vals) {
for (long val : vals) {
add(val);
}
}
/** {@inheritDoc} */
public void add(long[] vals, int offset, int length) {
for (int i = 0; i < length; i++) {
long val = vals[offset + i];
add(val);
}
}
/** {@inheritDoc} */
public void insert(int offset, long value) {
TLongLinkedList tmp = new TLongLinkedList();
tmp.add(value);
insert(offset, tmp);
}
/** {@inheritDoc} */
public void insert(int offset, long[] values) {
insert(offset, link(values, 0, values.length));
}
/** {@inheritDoc} */
public void insert(int offset, long[] values, int valOffset, int len) {
insert(offset, link(values, valOffset, len));
}
void insert(int offset, TLongLinkedList tmp) {
TLongLink l = getLinkAt(offset);
size = size + tmp.size;
//
if (l == head) {
// Add in front
tmp.tail.setNext(head);
head.setPrevious(tmp.tail);
head = tmp.head;
return;
}
if (no(l)) {
if (size == 0) {
// New empty list
head = tmp.head;
tail = tmp.tail;
} else {
// append
tail.setNext(tmp.head);
tmp.head.setPrevious(tail);
tail = tmp.tail;
}
} else {
TLongLink prev = l.getPrevious();
l.getPrevious().setNext(tmp.head);
// Link by behind tmp
tmp.tail.setNext(l);
l.setPrevious(tmp.tail);
tmp.head.setPrevious(prev);
}
}
static TLongLinkedList link(long[] values, int valOffset, int len) {
TLongLinkedList ret = new TLongLinkedList();
for (int i = 0; i < len; i++) {
ret.add(values[valOffset + i]);
}
return ret;
}
/** {@inheritDoc} */
public long get(int offset) {
if (offset > size)
throw new IndexOutOfBoundsException("index " + offset + " exceeds size " + size);
TLongLink l = getLinkAt(offset);
//
if (no(l))
return no_entry_value;
return l.getValue();
}
/**
* Returns the link at the given offset.
* <p/>
* A simple bisection criteria is used to keep the worst case complexity equal to
* O(n/2) where n = size(). Simply start from head of list or tail depending on offset
* and list size.
*
* @param offset of the link
* @return link or null if non-existent
*/
public TLongLink getLinkAt(int offset) {
if (offset >= size())
return null;
if (offset <= (size() >>> 1))
return getLink(head, 0, offset, true);
else
return getLink(tail, size() - 1, offset, false);
}
/**
* Returns the link at absolute offset starting from given the initial link 'l' at index 'idx'
*
* @param l
* @param idx
* @param offset
* @return
*/
private static TLongLink getLink(TLongLink l, int idx, int offset) {
return getLink(l, idx, offset, true);
}
/**
* Returns link at given absolute offset starting from link 'l' at index 'idx'
* @param l
* @param idx
* @param offset
* @param next
* @return
*/
private static TLongLink getLink(TLongLink l, int idx, int offset, boolean next) {
int i = idx;
//
while (got(l)) {
if (i == offset) {
return l;
}
i = i + (next ? 1 : -1);
l = next ? l.getNext() : l.getPrevious();
}
return null;
}
/** {@inheritDoc} */
public long set(int offset, long val) {
if (offset > size)
throw new IndexOutOfBoundsException("index " + offset + " exceeds size " + size);
TLongLink l = getLinkAt(offset);
//
if (no(l))
throw new IndexOutOfBoundsException("at offset " + offset);
long prev = l.getValue();
l.setValue(val);
return prev;
}
/** {@inheritDoc} */
public void set(int offset, long[] values) {
set(offset, values, 0, values.length);
}
/** {@inheritDoc} */
public void set(int offset, long[] values, int valOffset, int length) {
for (int i = 0; i < length; i++) {
long value = values[valOffset + i];
set(offset + i, value);
}
}
/** {@inheritDoc} */
public long replace(int offset, long val) {
return set(offset, val);
}
/** {@inheritDoc} */
public void clear() {
size = 0;
//
head = null;
tail = null;
}
/** {@inheritDoc} */
public boolean remove(long value) {
boolean changed = false;
for (TLongLink l = head; got(l); l = l.getNext()) {
//
if (l.getValue() == value) {
changed = true;
//
removeLink(l);
}
}
return changed;
}
/**
* unlinks the give TLongLink from the list
*
* @param l
*/
private void removeLink(TLongLink l) {
if (no(l))
return;
size--;
TLongLink prev = l.getPrevious();
TLongLink next = l.getNext();
if (got(prev)) {
prev.setNext(next);
} else {
// No previous we must be head
head = next;
}
if (got(next)) {
next.setPrevious(prev);
} else {
// No next so me must be tail
tail = prev;
}
// Unlink
l.setNext(null);
l.setPrevious(null);
}
/** {@inheritDoc} */
public boolean containsAll(Collection<?> collection) {
if (isEmpty())
return false;
for (Object o : collection) {
if (o instanceof Long) {
Long i = (Long) o;
if (!(contains(i)))
return false;
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll(TLongCollection collection) {
if (isEmpty())
return false;
for (TLongIterator it = collection.iterator(); it.hasNext();) {
long i = it.next();
if (!(contains(i)))
return false;
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll(long[] array) {
if (isEmpty())
return false;
for (long i : array) {
if (!contains(i))
return false;
}
return true;
}
/** {@inheritDoc} */
public boolean addAll(Collection<? extends Long> collection) {
boolean ret = false;
for (Long v : collection) {
if (add(v.longValue()))
ret = true;
}
return ret;
}
/** {@inheritDoc} */
public boolean addAll(TLongCollection collection) {
boolean ret = false;
for (TLongIterator it = collection.iterator(); it.hasNext();) {
long i = it.next();
if (add(i))
ret = true;
}
return ret;
}
/** {@inheritDoc} */
public boolean addAll(long[] array) {
boolean ret = false;
for (long i : array) {
if (add(i))
ret = true;
}
return ret;
}
/** {@inheritDoc} */
public boolean retainAll(Collection<?> collection) {
boolean modified = false;
TLongIterator iter = iterator();
while (iter.hasNext()) {
if (!collection.contains(Long.valueOf(iter.next()))) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll(TLongCollection collection) {
boolean modified = false;
TLongIterator iter = iterator();
while (iter.hasNext()) {
if (!collection.contains(iter.next())) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll(long[] array) {
Arrays.sort(array);
boolean modified = false;
TLongIterator iter = iterator();
while (iter.hasNext()) {
if (Arrays.binarySearch(array, iter.next()) < 0) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean removeAll(Collection<?> collection) {
boolean modified = false;
TLongIterator iter = iterator();
while (iter.hasNext()) {
if (collection.contains(Long.valueOf(iter.next()))) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean removeAll(TLongCollection collection) {
boolean modified = false;
TLongIterator iter = iterator();
while (iter.hasNext()) {
if (collection.contains(iter.next())) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean removeAll(long[] array) {
Arrays.sort(array);
boolean modified = false;
TLongIterator iter = iterator();
while (iter.hasNext()) {
if (Arrays.binarySearch(array, iter.next()) >= 0) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public long removeAt(int offset) {
TLongLink l = getLinkAt(offset);
if (no(l))
throw new ArrayIndexOutOfBoundsException("no elemenet at " + offset);
long prev = l.getValue();
removeLink(l);
return prev;
}
/** {@inheritDoc} */
public void remove(int offset, int length) {
for (int i = 0; i < length; i++) {
removeAt(offset); // since the list shrinks we don't need to use offset+i to get the next entry ;)
}
}
/** {@inheritDoc} */
public void transformValues(TLongFunction function) {
for (TLongLink l = head; got(l);) {
//
l.setValue(function.execute(l.getValue()));
//
l = l.getNext();
}
}
/** {@inheritDoc} */
public void reverse() {
TLongLink h = head;
TLongLink t = tail;
TLongLink prev, next, tmp;
//
TLongLink l = head;
while (got(l)) {
next = l.getNext();
prev = l.getPrevious();
//
tmp = l;
l = l.getNext();
//
tmp.setNext(prev);
tmp.setPrevious(next);
}
//
head = t;
tail = h;
}
/** {@inheritDoc} */
public void reverse(int from, int to) {
if (from > to)
throw new IllegalArgumentException("from > to : " + from + ">" + to);
TLongLink start = getLinkAt(from);
TLongLink stop = getLinkAt(to);
TLongLink prev, next;
TLongLink tmp = null;
TLongLink tmpHead = start.getPrevious();
//
TLongLink l = start;
while (l != stop) {
next = l.getNext();
prev = l.getPrevious();
//
tmp = l;
l = l.getNext();
//
tmp.setNext(prev);
tmp.setPrevious(next);
}
// At this point l == stop and tmp is the but last element {
if (got(tmp)) {
tmpHead.setNext(tmp);
stop.setPrevious(tmpHead);
}
start.setNext(stop);
stop.setPrevious(start);
}
/** {@inheritDoc} */
public void shuffle(Random rand) {
for (int i = 0; i < size; i++) {
TLongLink l = getLinkAt(rand.nextInt(size()));
removeLink(l);
add(l.getValue());
}
}
/** {@inheritDoc} */
public TLongList subList(int begin, int end) {
if (end < begin) {
throw new IllegalArgumentException("begin index " + begin +
" greater than end index " + end);
}
if (size < begin) {
throw new IllegalArgumentException("begin index " + begin +
" greater than last index " + size);
}
if (begin < 0) {
throw new IndexOutOfBoundsException("begin index can not be < 0");
}
if (end > size) {
throw new IndexOutOfBoundsException("end index < " + size);
}
TLongLinkedList ret = new TLongLinkedList();
TLongLink tmp = getLinkAt(begin);
for (int i = begin; i < end; i++) {
ret.add(tmp.getValue()); // copy
tmp = tmp.getNext();
}
return ret;
}
/** {@inheritDoc} */
public long[] toArray() {
return toArray(new long[size], 0, size);
}
/** {@inheritDoc} */
public long[] toArray(int offset, int len) {
return toArray(new long[len], offset, 0, len);
}
/** {@inheritDoc} */
public long[] toArray(long[] dest) {
return toArray(dest, 0, size);
}
/** {@inheritDoc} */
public long[] toArray(long[] dest, int offset, int len) {
return toArray(dest, offset, 0, len);
}
/** {@inheritDoc} */
public long[] toArray(long[] dest, int source_pos, int dest_pos, int len) {
if (len == 0) {
return dest; // nothing to copy
}
if (source_pos < 0 || source_pos >= size()) {
throw new ArrayIndexOutOfBoundsException(source_pos);
}
TLongLink tmp = getLinkAt(source_pos);
for (int i = 0; i < len; i++) {
dest[dest_pos + i] = tmp.getValue(); // copy
tmp = tmp.getNext();
}
return dest;
}
/** {@inheritDoc} */
public boolean forEach(TLongProcedure procedure) {
for (TLongLink l = head; got(l); l = l.getNext()) {
if (!procedure.execute(l.getValue()))
return false;
}
return true;
}
/** {@inheritDoc} */
public boolean forEachDescending(TLongProcedure procedure) {
for (TLongLink l = tail; got(l); l = l.getPrevious()) {
if (!procedure.execute(l.getValue()))
return false;
}
return true;
}
/** {@inheritDoc} */
public void sort() {
sort(0, size);
}
/** {@inheritDoc} */
public void sort(int fromIndex, int toIndex) {
TLongList tmp = subList(fromIndex, toIndex);
long[] vals = tmp.toArray();
Arrays.sort(vals);
set(fromIndex, vals);
}
/** {@inheritDoc} */
public void fill(long val) {
fill(0, size, val);
}
/** {@inheritDoc} */
public void fill(int fromIndex, int toIndex, long val) {
if (fromIndex < 0) {
throw new IndexOutOfBoundsException("begin index can not be < 0");
}
TLongLink l = getLinkAt(fromIndex);
if (toIndex > size) {
for (int i = fromIndex; i < size; i++) {
l.setValue(val);
l = l.getNext();
}
for (int i = size; i < toIndex; i++) {
add(val);
}
} else {
for (int i = fromIndex; i < toIndex; i++) {
l.setValue(val);
l = l.getNext();
}
}
}
/** {@inheritDoc} */
public int binarySearch(long value) {
return binarySearch(value, 0, size());
}
/** {@inheritDoc} */
public int binarySearch(long value, int fromIndex, int toIndex) {
if (fromIndex < 0) {
throw new IndexOutOfBoundsException("begin index can not be < 0");
}
if (toIndex > size) {
throw new IndexOutOfBoundsException("end index > size: " + toIndex + " > " + size);
}
if (toIndex < fromIndex) {
return -(fromIndex+1);
}
TLongLink middle;
int mid;
int from = fromIndex;
TLongLink fromLink = getLinkAt(fromIndex);
int to = toIndex;
while (from < to) {
mid = (from + to) >>> 1;
middle = getLink(fromLink, from, mid);
if (middle.getValue() == value)
return mid;
if (middle.getValue() < value) {
from = mid + 1;
fromLink = middle.next;
} else {
to = mid - 1;
}
}
return -(from + 1);
}
/** {@inheritDoc} */
public int indexOf(long value) {
return indexOf(0, value);
}
/** {@inheritDoc} */
public int indexOf(int offset, long value) {
int count = offset;
for (TLongLink l = getLinkAt(offset); got(l.getNext()); l = l.getNext()) {
if (l.getValue() == value)
return count;
count++;
}
return -1;
}
/** {@inheritDoc} */
public int lastIndexOf(long value) {
return lastIndexOf(0, value);
}
/** {@inheritDoc} */
public int lastIndexOf(int offset, long value) {
if (isEmpty())
return -1;
int last = -1;
int count = offset;
for (TLongLink l = getLinkAt(offset); got(l.getNext()); l = l.getNext()) {
if (l.getValue() == value)
last = count;
count++;
}
return last;
}
/** {@inheritDoc} */
public boolean contains(long value) {
if (isEmpty())
return false;
for (TLongLink l = head; got(l); l = l.getNext()) {
if (l.getValue() == value)
return true;
}
return false;
}
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongIterator() {
TLongLink l = head;
TLongLink current;
public long next() {
if (no(l))
throw new NoSuchElementException();
long ret = l.getValue();
current = l;
l = l.getNext();
return ret;
}
public boolean hasNext() {
return got(l);
}
public void remove() {
if (current == null)
throw new IllegalStateException();
removeLink(current);
current = null;
}
};
}
/** {@inheritDoc} */
public TLongList grep(TLongProcedure condition) {
TLongList ret = new TLongLinkedList();
for (TLongLink l = head; got(l); l = l.getNext()) {
if (condition.execute(l.getValue()))
ret.add(l.getValue());
}
return ret;
}
/** {@inheritDoc} */
public TLongList inverseGrep(TLongProcedure condition) {
TLongList ret = new TLongLinkedList();
for (TLongLink l = head; got(l); l = l.getNext()) {
if (!condition.execute(l.getValue()))
ret.add(l.getValue());
}
return ret;
}
/** {@inheritDoc} */
public long max() {
long ret = Long.MIN_VALUE;
if (isEmpty())
throw new IllegalStateException();
for (TLongLink l = head; got(l); l = l.getNext()) {
if (ret < l.getValue())
ret = l.getValue();
}
return ret;
}
/** {@inheritDoc} */
public long min() {
long ret = Long.MAX_VALUE;
if (isEmpty())
throw new IllegalStateException();
for (TLongLink l = head; got(l); l = l.getNext()) {
if (ret > l.getValue())
ret = l.getValue();
}
return ret;
}
/** {@inheritDoc} */
public long sum() {
long sum = 0;
for (TLongLink l = head; got(l); l = l.getNext()) {
sum += l.getValue();
}
return sum;
}
//
//
//
static class TLongLink {
long value;
TLongLink previous;
TLongLink next;
TLongLink(long value) {
this.value = value;
}
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
public TLongLink getPrevious() {
return previous;
}
public void setPrevious(TLongLink previous) {
this.previous = previous;
}
public TLongLink getNext() {
return next;
}
public void setNext(TLongLink next) {
this.next = next;
}
}
class RemoveProcedure implements TLongProcedure {
boolean changed = false;
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param value a value of type <code>int</code>
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute(long value) {
if (remove(value))
changed = true;
return true;
}
public boolean isChanged() {
return changed;
}
}
/** {@inheritDoc} */
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte(0);
// NO_ENTRY_VALUE
out.writeLong(no_entry_value);
// ENTRIES
out.writeInt(size);
for (TLongIterator iterator = iterator(); iterator.hasNext();) {
long next = iterator.next();
out.writeLong(next);
}
}
/** {@inheritDoc} */
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// NO_ENTRY_VALUE
no_entry_value = in.readLong();
// ENTRIES
int len = in.readInt();
for (int i = 0; i < len; i++) {
add(in.readLong());
}
}
static boolean got(Object ref) {
return ref != null;
}
static boolean no(Object ref) {
return ref == null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TLongLinkedList that = (TLongLinkedList) o;
if (no_entry_value != that.no_entry_value) return false;
if (size != that.size) return false;
TLongIterator iterator = iterator();
TLongIterator thatIterator = that.iterator();
while (iterator.hasNext()) {
if (!thatIterator.hasNext())
return false;
if (iterator.next() != thatIterator.next())
return false;
}
return true;
}
@Override
public int hashCode() {
int result = HashFunctions.hash(no_entry_value);
result = 31 * result + size;
for (TLongIterator iterator = iterator(); iterator.hasNext();) {
result = 31 * result + HashFunctions.hash(iterator.next());
}
return result;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder("{");
TLongIterator it = iterator();
while (it.hasNext()) {
long next = it.next();
buf.append(next);
if (it.hasNext())
buf.append(", ");
}
buf.append("}");
return buf.toString();
}
} // TLongLinkedList
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list.linked;
import gnu.trove.list.TLinkable;
import gnu.trove.procedure.TObjectProcedure;
import java.io.*;
import java.util.AbstractSequentialList;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.lang.reflect.Array;
/**
* <p>A LinkedList implementation which holds instances of type
* <tt>TLinkable</tt>.
* <p/>
* Using this implementation allows you to get java.util.LinkedList
* behavior (a doubly linked list, with Iterators that support insert
* and delete operations) without incurring the overhead of creating
* <tt>Node</tt> wrapper objects for every element in your list.
* <p/>
* The requirement to achieve this time/space gain is that the
* Objects stored in the List implement the <tt>TLinkable</tt>
* interface.
* <p/>
* The limitations are: <ul>
* <li>the same object cannot be put into more than one list at the same time.
* <li>the same object cannot be put into the same list more than once at the same time.
* <li>objects must only be removed from list they are in. That is,
* if you have an object A and lists l1 and l2, you must ensure that
* you invoke List.remove(A) on the correct list.
* <li> It is also forbidden to invoke List.remove() with an unaffiliated
* TLinkable (one that belongs to no list): this will destroy the list
* you invoke it on.
* </ul>
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: TLinkedList.java,v 1.1.2.3 2010/09/27 17:23:07 robeden Exp $
* @see gnu.trove.list.TLinkable
*/
public class TLinkedList<T extends TLinkable<T>> extends AbstractSequentialList<T>
implements Externalizable {
static final long serialVersionUID = 1L;
/** the head of the list */
protected T _head;
/** the tail of the list */
protected T _tail;
/** the number of elements in the list */
protected int _size = 0;
/** Creates a new <code>TLinkedList</code> instance. */
public TLinkedList() {
super();
}
/**
* Returns an iterator positioned at <tt>index</tt>. Assuming
* that the list has a value at that index, calling next() will
* retrieve and advance the iterator. Assuming that there is a
* value before <tt>index</tt> in the list, calling previous()
* will retrieve it (the value at index - 1) and move the iterator
* to that position. So, iterating from front to back starts at
* 0; iterating from back to front starts at <tt>size()</tt>.
*
* @param index an <code>int</code> value
* @return a <code>ListIterator</code> value
*/
public ListIterator<T> listIterator( int index ) {
return new IteratorImpl( index );
}
/**
* Returns the number of elements in the list.
*
* @return an <code>int</code> value
*/
public int size() {
return _size;
}
/**
* Inserts <tt>linkable</tt> at index <tt>index</tt> in the list.
* All values > index are shifted over one position to accommodate
* the new addition.
*
* @param index an <code>int</code> value
* @param linkable an object of type TLinkable
*/
public void add( int index, T linkable ) {
if ( index < 0 || index > size() ) {
throw new IndexOutOfBoundsException( "index:" + index );
}
insert( index, linkable );
}
/**
* Appends <tt>linkable</tt> to the end of the list.
*
* @param linkable an object of type TLinkable
* @return always true
*/
public boolean add( T linkable ) {
insert( _size, linkable );
return true;
}
/**
* Inserts <tt>linkable</tt> at the head of the list.
*
* @param linkable an object of type TLinkable
*/
public void addFirst( T linkable ) {
insert( 0, linkable );
}
/**
* Adds <tt>linkable</tt> to the end of the list.
*
* @param linkable an object of type TLinkable
*/
public void addLast( T linkable ) {
insert( size(), linkable );
}
/** Empties the list. */
public void clear() {
if ( null != _head ) {
for ( TLinkable<T> link = _head.getNext();
link != null;
link = link.getNext() ) {
TLinkable<T> prev = link.getPrevious();
prev.setNext( null );
link.setPrevious( null );
}
_head = _tail = null;
}
_size = 0;
}
/**
* Copies the list's contents into a native array. This will be a
* shallow copy: the Tlinkable instances in the Object[] array
* have links to one another: changing those will put this list
* into an unpredictable state. Holding a reference to one
* element in the list will prevent the others from being garbage
* collected unless you clear the next/previous links. <b>Caveat
* programmer!</b>
*
* @return an <code>Object[]</code> value
*/
public Object[] toArray() {
Object[] o = new Object[_size];
int i = 0;
for ( TLinkable link = _head; link != null; link = link.getNext() ) {
o[i++] = link;
}
return o;
}
/**
* Copies the list to a native array, destroying the next/previous
* links as the copy is made. This list will be emptied after the
* copy (as if clear() had been invoked). The Object[] array
* returned will contain TLinkables that do <b>not</b> hold
* references to one another and so are less likely to be the
* cause of memory leaks.
*
* @return an <code>Object[]</code> value
*/
public Object[] toUnlinkedArray() {
Object[] o = new Object[_size];
int i = 0;
for ( TLinkable<T> link = _head, tmp; link != null; i++ ) {
o[i] = link;
tmp = link;
link = link.getNext();
tmp.setNext( null ); // clear the links
tmp.setPrevious( null );
}
_size = 0; // clear the list
_head = _tail = null;
return o;
}
/**
* Returns a typed array of the objects in the set.
*
* @param a an <code>Object[]</code> value
* @return an <code>Object[]</code> value
*/
@SuppressWarnings({"unchecked"})
public T[] toUnlinkedArray( T[] a ) {
int size = size();
if ( a.length < size ) {
a = (T[]) Array.newInstance( a.getClass().getComponentType(), size );
}
int i = 0;
for ( T link = _head, tmp; link != null; i++ ) {
a[i] = link;
tmp = link;
link = link.getNext();
tmp.setNext( null ); // clear the links
tmp.setPrevious( null );
}
_size = 0; // clear the list
_head = _tail = null;
return a;
}
/**
* A linear search for <tt>o</tt> in the list.
*
* @param o an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( Object o ) {
for ( TLinkable<T> link = _head; link != null; link = link.getNext() ) {
if ( o.equals( link ) ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
@Override
@SuppressWarnings({"unchecked"})
public T get( int index ) {
// Blow out for bogus values
if ( index < 0 || index >= _size ) {
throw new IndexOutOfBoundsException( "Index: " + index + ", Size: " + _size );
}
// Determine if it's better to get there from the front or the back
if ( index > ( _size >> 1 ) ) {
int position = _size - 1;
T node = _tail;
while ( position > index ) {
node = node.getPrevious();
position--;
}
return node;
} else {
int position = 0;
T node = _head;
while ( position < index ) {
node = node.getNext();
position++;
}
return node;
}
}
/**
* Returns the head of the list
*
* @return an <code>Object</code> value
*/
public T getFirst() {
return _head;
}
/**
* Returns the tail of the list.
*
* @return an <code>Object</code> value
*/
public T getLast() {
return _tail;
}
/**
* Return the node following the given node. This method exists for two reasons:
* <ol>
* <li>It's really not recommended that the methods implemented by TLinkable be
* called directly since they're used internally by this class.</li>
* <li>This solves problems arising from generics when working with the linked
* objects directly.</li>
* </ol>
* <p/>
* NOTE: this should only be used with nodes contained in the list. The results are
* undefined with anything else.
*
* @param current The current node
* @return the node after the current node
*/
@SuppressWarnings({"unchecked"})
public T getNext( T current ) {
return current.getNext();
}
/**
* Return the node preceding the given node. This method exists for two reasons:
* <ol>
* <li>It's really not recommended that the methods implemented by TLinkable be
* called directly since they're used internally by this class.</li>
* <li>This solves problems arising from generics when working with the linked
* objects directly.</li>
* </ol>
* <p/>
* NOTE: this should only be used with nodes contained in the list. The results are
* undefined with anything else.
*
* @param current The current node
* @return the node after the current node
*/
@SuppressWarnings({"unchecked"})
public T getPrevious( T current ) {
return current.getPrevious();
}
/**
* Remove and return the first element in the list.
*
* @return an <code>Object</code> value
*/
@SuppressWarnings({"unchecked"})
public T removeFirst() {
T o = _head;
if ( o == null ) {
return null;
}
T n = o.getNext();
o.setNext( null );
if ( null != n ) {
n.setPrevious( null );
}
_head = n;
if ( --_size == 0 ) {
_tail = null;
}
return o;
}
/**
* Remove and return the last element in the list.
*
* @return an <code>Object</code> value
*/
@SuppressWarnings({"unchecked"})
public T removeLast() {
T o = _tail;
if ( o == null ) {
return null;
}
T prev = o.getPrevious();
o.setPrevious( null );
if ( null != prev ) {
prev.setNext( null );
}
_tail = prev;
if ( --_size == 0 ) {
_head = null;
}
return o;
}
/**
* Implementation of index-based list insertions.
*
* @param index an <code>int</code> value
* @param linkable an object of type TLinkable
*/
@SuppressWarnings({"unchecked"})
protected void insert( int index, T linkable ) {
if ( _size == 0 ) {
_head = _tail = linkable; // first insertion
} else if ( index == 0 ) {
linkable.setNext( _head ); // insert at front
_head.setPrevious( linkable );
_head = linkable;
} else if ( index == _size ) { // insert at back
_tail.setNext( linkable );
linkable.setPrevious( _tail );
_tail = linkable;
} else {
T node = get( index );
T before = node.getPrevious();
if ( before != null ) {
before.setNext( linkable );
}
linkable.setPrevious( before );
linkable.setNext( node );
node.setPrevious( linkable );
}
_size++;
}
/**
* Removes the specified element from the list. Note that
* it is the caller's responsibility to ensure that the
* element does, in fact, belong to this list and not another
* instance of TLinkedList.
*
* @param o a TLinkable element already inserted in this list.
* @return true if the element was a TLinkable and removed
*/
@SuppressWarnings({"unchecked"})
public boolean remove( Object o ) {
if ( o instanceof TLinkable ) {
T p, n;
TLinkable<T> link = (TLinkable<T>) o;
p = link.getPrevious();
n = link.getNext();
if ( n == null && p == null ) { // emptying the list
// It's possible this object is not something that's in the list. So,
// make sure it's the head if it doesn't point to anything. This solves
// problems caused by removing something multiple times.
if ( o != _head ) {
return false;
}
_head = _tail = null;
} else if ( n == null ) { // this is the tail
// make previous the new tail
link.setPrevious( null );
p.setNext( null );
_tail = p;
} else if ( p == null ) { // this is the head
// make next the new head
link.setNext( null );
n.setPrevious( null );
_head = n;
} else { // somewhere in the middle
p.setNext( n );
n.setPrevious( p );
link.setNext( null );
link.setPrevious( null );
}
_size--; // reduce size of list
return true;
} else {
return false;
}
}
/**
* Inserts newElement into the list immediately before current.
* All elements to the right of and including current are shifted
* over.
*
* @param current a <code>TLinkable</code> value currently in the list.
* @param newElement a <code>TLinkable</code> value to be added to
* the list.
*/
public void addBefore( T current, T newElement ) {
if ( current == _head ) {
addFirst( newElement );
} else if ( current == null ) {
addLast( newElement );
} else {
T p = current.getPrevious();
newElement.setNext( current );
p.setNext( newElement );
newElement.setPrevious( p );
current.setPrevious( newElement );
_size++;
}
}
/**
* Inserts newElement into the list immediately after current.
* All elements to the left of and including current are shifted
* over.
*
* @param current a <code>TLinkable</code> value currently in the list.
* @param newElement a <code>TLinkable</code> value to be added to
* the list.
*/
public void addAfter( T current, T newElement ) {
if ( current == _tail ) {
addLast( newElement );
} else if ( current == null ) {
addFirst( newElement );
} else {
T n = current.getNext();
newElement.setPrevious( current );
newElement.setNext( n );
current.setNext( newElement );
n.setPrevious( newElement );
_size++;
}
}
/**
* Executes <tt>procedure</tt> for each entry in the list.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
@SuppressWarnings({"unchecked"})
public boolean forEachValue( TObjectProcedure<T> procedure ) {
T node = _head;
while ( node != null ) {
boolean keep_going = procedure.execute( node );
if ( !keep_going ) {
return false;
}
node = node.getNext();
}
return true;
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// NUMBER OF ENTRIES
out.writeInt( _size );
// HEAD
out.writeObject( _head );
// TAIL
out.writeObject( _tail );
}
@SuppressWarnings({"unchecked"})
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// NUMBER OF ENTRIED
_size = in.readInt();
// HEAD
_head = (T) in.readObject();
// TAIL
_tail = (T) in.readObject();
}
/** A ListIterator that supports additions and deletions. */
protected final class IteratorImpl implements ListIterator<T> {
private int _nextIndex = 0;
private T _next;
private T _lastReturned;
/**
* Creates a new <code>Iterator</code> instance positioned at
* <tt>index</tt>.
*
* @param position an <code>int</code> value
*/
@SuppressWarnings({"unchecked"})
IteratorImpl( int position ) {
if ( position < 0 || position > _size ) {
throw new IndexOutOfBoundsException();
}
_nextIndex = position;
if ( position == 0 ) {
_next = _head;
} else if ( position == _size ) {
_next = null;
} else if ( position < ( _size >> 1 ) ) {
int pos = 0;
for ( _next = _head; pos < position; pos++ ) {
_next = _next.getNext();
}
} else {
int pos = _size - 1;
for ( _next = _tail; pos > position; pos-- ) {
_next = _next.getPrevious();
}
}
}
/**
* Insert <tt>linkable</tt> at the current position of the iterator.
* Calling next() after add() will return the added object.
*
* @param linkable an object of type TLinkable
*/
public final void add( T linkable ) {
_lastReturned = null;
_nextIndex++;
if ( _size == 0 ) {
TLinkedList.this.add( linkable );
} else {
TLinkedList.this.addBefore( _next, linkable );
}
}
/**
* True if a call to next() will return an object.
*
* @return a <code>boolean</code> value
*/
public final boolean hasNext() {
return _nextIndex != _size;
}
/**
* True if a call to previous() will return a value.
*
* @return a <code>boolean</code> value
*/
public final boolean hasPrevious() {
return _nextIndex != 0;
}
/**
* Returns the value at the Iterator's index and advances the
* iterator.
*
* @return an <code>Object</code> value
* @throws NoSuchElementException if there is no next element
*/
@SuppressWarnings({"unchecked"})
public final T next() {
if ( _nextIndex == _size ) {
throw new NoSuchElementException();
}
_lastReturned = _next;
_next = _next.getNext();
_nextIndex++;
return _lastReturned;
}
/**
* returns the index of the next node in the list (the
* one that would be returned by a call to next()).
*
* @return an <code>int</code> value
*/
public final int nextIndex() {
return _nextIndex;
}
/**
* Returns the value before the Iterator's index and moves the
* iterator back one index.
*
* @return an <code>Object</code> value
* @throws NoSuchElementException if there is no previous element.
*/
@SuppressWarnings({"unchecked"})
public final T previous() {
if ( _nextIndex == 0 ) {
throw new NoSuchElementException();
}
if ( _nextIndex == _size ) {
_lastReturned = _next = _tail;
} else {
_lastReturned = _next = _next.getPrevious();
}
_nextIndex--;
return _lastReturned;
}
/**
* Returns the previous element's index.
*
* @return an <code>int</code> value
*/
public final int previousIndex() {
return _nextIndex - 1;
}
/**
* Removes the current element in the list and shrinks its
* size accordingly.
*
* @throws IllegalStateException neither next nor previous
* have been invoked, or remove or add have been invoked after
* the last invocation of next or previous.
*/
@SuppressWarnings({"unchecked"})
public final void remove() {
if ( _lastReturned == null ) {
throw new IllegalStateException( "must invoke next or previous before invoking remove" );
}
if ( _lastReturned != _next ) {
_nextIndex--;
}
_next = _lastReturned.getNext();
TLinkedList.this.remove( _lastReturned );
_lastReturned = null;
}
/**
* Replaces the current element in the list with
* <tt>linkable</tt>
*
* @param linkable an object of type TLinkable
*/
public final void set( T linkable ) {
if ( _lastReturned == null ) {
throw new IllegalStateException();
}
swap( _lastReturned, linkable );
_lastReturned = linkable;
}
/**
* Replace from with to in the list.
*
* @param from a <code>TLinkable</code> value
* @param to a <code>TLinkable</code> value
*/
private void swap( T from, T to ) {
T from_p = from.getPrevious();
T from_n = from.getNext();
T to_p = to.getPrevious();
T to_n = to.getNext();
// NOTE: 'to' cannot be null at this point
if ( from_n == to ) {
if ( from_p != null ) from_p.setNext( to );
to.setPrevious( from_p );
to.setNext( from );
from.setPrevious( to );
from.setNext( to_n );
if ( to_n != null ) to_n.setPrevious( from );
}
// NOTE: 'from' cannot be null at this point
else if ( to_n == from ) {
if ( to_p != null ) to_p.setNext( to );
to.setPrevious( from );
to.setNext( from_n );
from.setPrevious( to_p );
from.setNext( to );
if ( from_n != null ) from_n.setPrevious( to );
}
else {
from.setNext( to_n );
from.setPrevious( to_p );
if ( to_p != null ) to_p.setNext( from );
if ( to_n != null ) to_n.setPrevious( from );
to.setNext( from_n );
to.setPrevious( from_p );
if ( from_p != null ) from_p.setNext( to );
if ( from_n != null ) from_n.setPrevious( to );
}
if ( _head == from ) _head = to;
else if ( _head == to ) _head = from;
if ( _tail == from ) _tail = to;
else if ( _tail == to ) _tail = from;
if ( _lastReturned == from ) _lastReturned = to;
else if ( _lastReturned == to ) _lastReturned = from;
if ( _next == from ) _next = to;
else if ( _next == to ) _next = from;
}
}
} // TLinkedList
| Java |
package gnu.trove.list;
/**
* Simple adapter class implementing {@link TLinkable}, so you don't have to. Example:
* <pre>
private class MyObject extends TLinkableAdapter<MyObject> {
private final String value;
MyObject( String value ) {
this.value = value;
}
public String getValue() {
return value;
}
}
* </pre>
*/
public abstract class TLinkableAdapter<T extends TLinkable> implements TLinkable<T> {
private volatile T next;
private volatile T prev;
@Override
public T getNext() {
return next;
}
@Override
public void setNext( T next ) {
this.next = next;
}
@Override
public T getPrevious() {
return prev;
}
@Override
public void setPrevious( T prev ) {
this.prev = prev;
}
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.function.*;
import gnu.trove.procedure.*;
import gnu.trove.TIntCollection;
import java.io.Serializable;
import java.util.Random;
/**
* Interface for Trove list implementations.
*/
public interface TIntList extends TIntCollection {
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryValue();
/**
* Returns the number of values in the list.
*
* @return the number of values in the list.
*/
public int size();
/**
* Tests whether this list contains any values.
*
* @return true if the list is empty.
*/
public boolean isEmpty();
/**
* Adds <tt>val</tt> to the end of the list, growing as needed.
*
* @param val an <code>int</code> value
* @return true if the list was modified by the add operation
*/
public boolean add(int val);
/**
* Adds the values in the array <tt>vals</tt> to the end of the
* list, in order.
*
* @param vals an <code>int[]</code> value
*/
public void add( int[] vals );
/**
* Adds a subset of the values in the array <tt>vals</tt> to the
* end of the list, in order.
*
* @param vals an <code>int[]</code> value
* @param offset the offset at which to start copying
* @param length the number of values to copy.
*/
public void add( int[] vals, int offset, int length );
/**
* Inserts <tt>value</tt> into the list at <tt>offset</tt>. All
* values including and to the right of <tt>offset</tt> are shifted
* to the right.
*
* @param offset an <code>int</code> value
* @param value an <code>int</code> value
*/
public void insert( int offset, int value );
/**
* Inserts the array of <tt>values</tt> into the list at
* <tt>offset</tt>. All values including and to the right of
* <tt>offset</tt> are shifted to the right.
*
* @param offset an <code>int</code> value
* @param values an <code>int[]</code> value
*/
public void insert( int offset, int[] values );
/**
* Inserts a slice of the array of <tt>values</tt> into the list
* at <tt>offset</tt>. All values including and to the right of
* <tt>offset</tt> are shifted to the right.
*
* @param offset an <code>int</code> value
* @param values an <code>int[]</code> value
* @param valOffset the offset in the values array at which to
* start copying.
* @param len the number of values to copy from the values array
*/
public void insert( int offset, int[] values, int valOffset, int len );
/**
* Returns the value at the specified offset.
*
* @param offset an <code>int</code> value
* @return an <code>int</code> value
*/
public int get( int offset );
/**
* Sets the value at the specified offset.
*
* @param offset an <code>int</code> value
* @param val an <code>int</code> value
*
* @return The value previously at the given index.
*/
public int set( int offset, int val );
/**
* Replace the values in the list starting at <tt>offset</tt> with
* the contents of the <tt>values</tt> array.
*
* @param offset the first offset to replace
* @param values the source of the new values
*/
public void set( int offset, int[] values );
/**
* Replace the values in the list starting at <tt>offset</tt> with
* <tt>length</tt> values from the <tt>values</tt> array, starting
* at valOffset.
*
* @param offset the first offset to replace
* @param values the source of the new values
* @param valOffset the first value to copy from the values array
* @param length the number of values to copy
*/
public void set( int offset, int[] values, int valOffset, int length );
/**
* Sets the value at the specified offset and returns the
* previously stored value.
*
* @param offset an <code>int</code> value
* @param val an <code>int</code> value
* @return the value previously stored at offset.
*/
public int replace( int offset, int val );
/**
* Flushes the internal state of the list, resetting the capacity
* to the default.
*/
public void clear();
/**
* Removes <tt>value</tt> from the list.
*
* @param value an <code>int</code> value
* @return true if the list was modified by the remove operation.
*/
public boolean remove( int value );
/**
* Removes <tt>value</tt> at a given offset from the list.
*
* @param offset an <code>int</code> value that represents
* the offset to the element to be removed
* @return an <tt>int</tt> that is the value removed.
*/
public int removeAt( int offset );
/**
* Removes <tt>length</tt> values from the list, starting at
* <tt>offset</tt>
*
* @param offset an <code>int</code> value
* @param length an <code>int</code> value
*/
public void remove( int offset, int length );
/**
* Transform each value in the list using the specified function.
*
* @param function a <code>TIntFunction</code> value
*/
public void transformValues( TIntFunction function );
/**
* Reverse the order of the elements in the list.
*/
public void reverse();
/**
* Reverse the order of the elements in the range of the list.
*
* @param from the inclusive index at which to start reversing
* @param to the exclusive index at which to stop reversing
*/
public void reverse( int from, int to );
/**
* Shuffle the elements of the list using the specified random
* number generator.
*
* @param rand a <code>Random</code> value
*/
public void shuffle( Random rand );
/**
* Returns a sublist of this list.
*
* @param begin low endpoint (inclusive) of the subList.
* @param end high endpoint (exclusive) of the subList.
* @return sublist of this list from begin, inclusive to end, exclusive.
* @throws IndexOutOfBoundsException - endpoint out of range
* @throws IllegalArgumentException - endpoints out of order (end > begin)
*/
public TIntList subList( int begin, int end );
/**
* Copies the contents of the list into a native array.
*
* @return an <code>int[]</code> value
*/
public int[] toArray();
/**
* Copies a slice of the list into a native array.
*
* @param offset the offset at which to start copying
* @param len the number of values to copy.
* @return an <code>int[]</code> value
*/
public int[] toArray( int offset, int len );
/**
* Copies a slice of the list into a native array.
*
* <p>If the list fits in the specified array with room to spare (i.e.,
* the array has more elements than the list), the element in the array
* immediately following the end of the list is set to
* <tt>{@link #getNoEntryValue()}</tt>.
* (This is useful in determining the length of the list <i>only</i> if
* the caller knows that the list does not contain any "null" elements.)
*
* <p>NOTE: Trove does not allocate a new array if the array passed in is
* not large enough to hold all of the data elements. It will instead fill
* the array passed in.
*
* @param dest the array to copy into.
* @return the array passed in.
*/
public int[] toArray( int[] dest );
/**
* Copies a slice of the list into a native array.
*
* @param dest the array to copy into.
* @param offset the offset where the first value should be copied
* @param len the number of values to copy.
* @return the array passed in.
*/
public int[] toArray( int[] dest, int offset, int len );
/**
* Copies a slice of the list into a native array.
*
* @param dest the array to copy into.
* @param source_pos the offset of the first value to copy
* @param dest_pos the offset where the first value should be copied
* @param len the number of values to copy.
* @return the array passed in.
*/
public int[] toArray( int[] dest, int source_pos, int dest_pos, int len );
/**
* Applies the procedure to each value in the list in ascending
* (front to back) order.
*
* @param procedure a <code>TIntProcedure</code> value
* @return true if the procedure did not terminate prematurely.
*/
public boolean forEach( TIntProcedure procedure );
/**
* Applies the procedure to each value in the list in descending
* (back to front) order.
*
* @param procedure a <code>TIntProcedure</code> value
* @return true if the procedure did not terminate prematurely.
*/
public boolean forEachDescending( TIntProcedure procedure );
/**
* Sort the values in the list (ascending) using the Sun quicksort
* implementation.
*
* @see java.util.Arrays#sort
*/
public void sort();
/**
* Sort a slice of the list (ascending) using the Sun quicksort
* implementation.
*
* @param fromIndex the index at which to start sorting (inclusive)
* @param toIndex the index at which to stop sorting (exclusive)
* @see java.util.Arrays#sort
*/
public void sort( int fromIndex, int toIndex );
/**
* Fills every slot in the list with the specified value.
*
* @param val the value to use when filling
*/
public void fill( int val );
/**
* Fills a range in the list with the specified value.
*
* @param fromIndex the offset at which to start filling (inclusive)
* @param toIndex the offset at which to stop filling (exclusive)
* @param val the value to use when filling
*/
public void fill( int fromIndex, int toIndex, int val );
/**
* Performs a binary search for <tt>value</tt> in the entire list.
* Note that you <b>must</b> @{link #sort sort} the list before
* doing a search.
*
* @param value the value to search for
* @return the absolute offset in the list of the value, or its
* negative insertion point into the sorted list.
*/
public int binarySearch( int value );
/**
* Performs a binary search for <tt>value</tt> in the specified
* range. Note that you <b>must</b> @{link #sort sort} the list
* or the range before doing a search.
*
* @param value the value to search for
* @param fromIndex the lower boundary of the range (inclusive)
* @param toIndex the upper boundary of the range (exclusive)
* @return the absolute offset in the list of the value, or its
* negative insertion point into the sorted list.
*/
public int binarySearch( int value, int fromIndex, int toIndex );
/**
* Searches the list front to back for the index of
* <tt>value</tt>.
*
* @param value an <code>int</code> value
* @return the first offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int indexOf( int value );
/**
* Searches the list front to back for the index of
* <tt>value</tt>, starting at <tt>offset</tt>.
*
* @param offset the offset at which to start the linear search
* (inclusive)
* @param value an <code>int</code> value
* @return the first offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int indexOf( int offset, int value );
/**
* Searches the list back to front for the last index of
* <tt>value</tt>.
*
* @param value an <code>int</code> value
* @return the last offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int lastIndexOf( int value );
/**
* Searches the list back to front for the last index of
* <tt>value</tt>, starting at <tt>offset</tt>.
*
* @param offset the offset at which to start the linear search
* (exclusive)
* @param value an <code>int</code> value
* @return the last offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int lastIndexOf( int offset, int value );
/**
* Searches the list for <tt>value</tt>
*
* @param value an <code>int</code> value
* @return true if value is in the list.
*/
public boolean contains( int value );
/**
* Searches the list for values satisfying <tt>condition</tt> in
* the manner of the *nix <tt>grep</tt> utility.
*
* @param condition a condition to apply to each element in the list
* @return a list of values which match the condition.
*/
public TIntList grep( TIntProcedure condition );
/**
* Searches the list for values which do <b>not</b> satisfy
* <tt>condition</tt>. This is akin to *nix <code>grep -v</code>.
*
* @param condition a condition to apply to each element in the list
* @return a list of values which do not match the condition.
*/
public TIntList inverseGrep( TIntProcedure condition );
/**
* Finds the maximum value in the list.
*
* @return the largest value in the list.
* @exception IllegalStateException if the list is empty
*/
public int max();
/**
* Finds the minimum value in the list.
*
* @return the smallest value in the list.
* @exception IllegalStateException if the list is empty
*/
public int min();
/**
* Calculates the sum of all the values in the list.
*
* @return the sum of the values in the list (zero if the list is empty).
*/
public int sum();
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list;
import java.io.Serializable;
/**
* Interface for Objects which can be inserted into a TLinkedList.
*
* @author Eric D. Friedman
* @version $Id: TLinkable.java,v 1.1.2.2 2009/09/04 12:32:33 upholderoftruth Exp $
* @see gnu.trove.list.linked.TLinkedList
*/
public interface TLinkable<T extends TLinkable> extends Serializable {
static final long serialVersionUID = 997545054865482562L;
/**
* Returns the linked list node after this one.
*
* @return a <code>TLinkable</code> value
*/
public T getNext();
/**
* Returns the linked list node before this one.
*
* @return a <code>TLinkable</code> value
*/
public T getPrevious();
/**
* Sets the linked list node after this one.
*
* @param linkable a <code>TLinkable</code> value
*/
public void setNext( T linkable );
/**
* Sets the linked list node before this one.
*
* @param linkable a <code>TLinkable</code> value
*/
public void setPrevious( T linkable );
}// TLinkable
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.function.*;
import gnu.trove.procedure.*;
import gnu.trove.TLongCollection;
import java.io.Serializable;
import java.util.Random;
/**
* Interface for Trove list implementations.
*/
public interface TLongList extends TLongCollection {
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryValue();
/**
* Returns the number of values in the list.
*
* @return the number of values in the list.
*/
public int size();
/**
* Tests whether this list contains any values.
*
* @return true if the list is empty.
*/
public boolean isEmpty();
/**
* Adds <tt>val</tt> to the end of the list, growing as needed.
*
* @param val an <code>long</code> value
* @return true if the list was modified by the add operation
*/
public boolean add(long val);
/**
* Adds the values in the array <tt>vals</tt> to the end of the
* list, in order.
*
* @param vals an <code>long[]</code> value
*/
public void add( long[] vals );
/**
* Adds a subset of the values in the array <tt>vals</tt> to the
* end of the list, in order.
*
* @param vals an <code>long[]</code> value
* @param offset the offset at which to start copying
* @param length the number of values to copy.
*/
public void add( long[] vals, int offset, int length );
/**
* Inserts <tt>value</tt> into the list at <tt>offset</tt>. All
* values including and to the right of <tt>offset</tt> are shifted
* to the right.
*
* @param offset an <code>int</code> value
* @param value an <code>long</code> value
*/
public void insert( int offset, long value );
/**
* Inserts the array of <tt>values</tt> into the list at
* <tt>offset</tt>. All values including and to the right of
* <tt>offset</tt> are shifted to the right.
*
* @param offset an <code>int</code> value
* @param values an <code>long[]</code> value
*/
public void insert( int offset, long[] values );
/**
* Inserts a slice of the array of <tt>values</tt> into the list
* at <tt>offset</tt>. All values including and to the right of
* <tt>offset</tt> are shifted to the right.
*
* @param offset an <code>int</code> value
* @param values an <code>long[]</code> value
* @param valOffset the offset in the values array at which to
* start copying.
* @param len the number of values to copy from the values array
*/
public void insert( int offset, long[] values, int valOffset, int len );
/**
* Returns the value at the specified offset.
*
* @param offset an <code>int</code> value
* @return an <code>long</code> value
*/
public long get( int offset );
/**
* Sets the value at the specified offset.
*
* @param offset an <code>int</code> value
* @param val an <code>long</code> value
*
* @return The value previously at the given index.
*/
public long set( int offset, long val );
/**
* Replace the values in the list starting at <tt>offset</tt> with
* the contents of the <tt>values</tt> array.
*
* @param offset the first offset to replace
* @param values the source of the new values
*/
public void set( int offset, long[] values );
/**
* Replace the values in the list starting at <tt>offset</tt> with
* <tt>length</tt> values from the <tt>values</tt> array, starting
* at valOffset.
*
* @param offset the first offset to replace
* @param values the source of the new values
* @param valOffset the first value to copy from the values array
* @param length the number of values to copy
*/
public void set( int offset, long[] values, int valOffset, int length );
/**
* Sets the value at the specified offset and returns the
* previously stored value.
*
* @param offset an <code>int</code> value
* @param val an <code>long</code> value
* @return the value previously stored at offset.
*/
public long replace( int offset, long val );
/**
* Flushes the internal state of the list, resetting the capacity
* to the default.
*/
public void clear();
/**
* Removes <tt>value</tt> from the list.
*
* @param value an <code>long</code> value
* @return true if the list was modified by the remove operation.
*/
public boolean remove( long value );
/**
* Removes <tt>value</tt> at a given offset from the list.
*
* @param offset an <code>int</code> value that represents
* the offset to the element to be removed
* @return an <tt>long</tt> that is the value removed.
*/
public long removeAt( int offset );
/**
* Removes <tt>length</tt> values from the list, starting at
* <tt>offset</tt>
*
* @param offset an <code>int</code> value
* @param length an <code>int</code> value
*/
public void remove( int offset, int length );
/**
* Transform each value in the list using the specified function.
*
* @param function a <code>TLongFunction</code> value
*/
public void transformValues( TLongFunction function );
/**
* Reverse the order of the elements in the list.
*/
public void reverse();
/**
* Reverse the order of the elements in the range of the list.
*
* @param from the inclusive index at which to start reversing
* @param to the exclusive index at which to stop reversing
*/
public void reverse( int from, int to );
/**
* Shuffle the elements of the list using the specified random
* number generator.
*
* @param rand a <code>Random</code> value
*/
public void shuffle( Random rand );
/**
* Returns a sublist of this list.
*
* @param begin low endpoint (inclusive) of the subList.
* @param end high endpoint (exclusive) of the subList.
* @return sublist of this list from begin, inclusive to end, exclusive.
* @throws IndexOutOfBoundsException - endpoint out of range
* @throws IllegalArgumentException - endpoints out of order (end > begin)
*/
public TLongList subList( int begin, int end );
/**
* Copies the contents of the list into a native array.
*
* @return an <code>long[]</code> value
*/
public long[] toArray();
/**
* Copies a slice of the list into a native array.
*
* @param offset the offset at which to start copying
* @param len the number of values to copy.
* @return an <code>long[]</code> value
*/
public long[] toArray( int offset, int len );
/**
* Copies a slice of the list into a native array.
*
* <p>If the list fits in the specified array with room to spare (i.e.,
* the array has more elements than the list), the element in the array
* immediately following the end of the list is set to
* <tt>{@link #getNoEntryValue()}</tt>.
* (This is useful in determining the length of the list <i>only</i> if
* the caller knows that the list does not contain any "null" elements.)
*
* <p>NOTE: Trove does not allocate a new array if the array passed in is
* not large enough to hold all of the data elements. It will instead fill
* the array passed in.
*
* @param dest the array to copy into.
* @return the array passed in.
*/
public long[] toArray( long[] dest );
/**
* Copies a slice of the list into a native array.
*
* @param dest the array to copy into.
* @param offset the offset where the first value should be copied
* @param len the number of values to copy.
* @return the array passed in.
*/
public long[] toArray( long[] dest, int offset, int len );
/**
* Copies a slice of the list into a native array.
*
* @param dest the array to copy into.
* @param source_pos the offset of the first value to copy
* @param dest_pos the offset where the first value should be copied
* @param len the number of values to copy.
* @return the array passed in.
*/
public long[] toArray( long[] dest, int source_pos, int dest_pos, int len );
/**
* Applies the procedure to each value in the list in ascending
* (front to back) order.
*
* @param procedure a <code>TLongProcedure</code> value
* @return true if the procedure did not terminate prematurely.
*/
public boolean forEach( TLongProcedure procedure );
/**
* Applies the procedure to each value in the list in descending
* (back to front) order.
*
* @param procedure a <code>TLongProcedure</code> value
* @return true if the procedure did not terminate prematurely.
*/
public boolean forEachDescending( TLongProcedure procedure );
/**
* Sort the values in the list (ascending) using the Sun quicksort
* implementation.
*
* @see java.util.Arrays#sort
*/
public void sort();
/**
* Sort a slice of the list (ascending) using the Sun quicksort
* implementation.
*
* @param fromIndex the index at which to start sorting (inclusive)
* @param toIndex the index at which to stop sorting (exclusive)
* @see java.util.Arrays#sort
*/
public void sort( int fromIndex, int toIndex );
/**
* Fills every slot in the list with the specified value.
*
* @param val the value to use when filling
*/
public void fill( long val );
/**
* Fills a range in the list with the specified value.
*
* @param fromIndex the offset at which to start filling (inclusive)
* @param toIndex the offset at which to stop filling (exclusive)
* @param val the value to use when filling
*/
public void fill( int fromIndex, int toIndex, long val );
/**
* Performs a binary search for <tt>value</tt> in the entire list.
* Note that you <b>must</b> @{link #sort sort} the list before
* doing a search.
*
* @param value the value to search for
* @return the absolute offset in the list of the value, or its
* negative insertion point into the sorted list.
*/
public int binarySearch( long value );
/**
* Performs a binary search for <tt>value</tt> in the specified
* range. Note that you <b>must</b> @{link #sort sort} the list
* or the range before doing a search.
*
* @param value the value to search for
* @param fromIndex the lower boundary of the range (inclusive)
* @param toIndex the upper boundary of the range (exclusive)
* @return the absolute offset in the list of the value, or its
* negative insertion point into the sorted list.
*/
public int binarySearch( long value, int fromIndex, int toIndex );
/**
* Searches the list front to back for the index of
* <tt>value</tt>.
*
* @param value an <code>long</code> value
* @return the first offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int indexOf( long value );
/**
* Searches the list front to back for the index of
* <tt>value</tt>, starting at <tt>offset</tt>.
*
* @param offset the offset at which to start the linear search
* (inclusive)
* @param value an <code>long</code> value
* @return the first offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int indexOf( int offset, long value );
/**
* Searches the list back to front for the last index of
* <tt>value</tt>.
*
* @param value an <code>long</code> value
* @return the last offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int lastIndexOf( long value );
/**
* Searches the list back to front for the last index of
* <tt>value</tt>, starting at <tt>offset</tt>.
*
* @param offset the offset at which to start the linear search
* (exclusive)
* @param value an <code>long</code> value
* @return the last offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int lastIndexOf( int offset, long value );
/**
* Searches the list for <tt>value</tt>
*
* @param value an <code>long</code> value
* @return true if value is in the list.
*/
public boolean contains( long value );
/**
* Searches the list for values satisfying <tt>condition</tt> in
* the manner of the *nix <tt>grep</tt> utility.
*
* @param condition a condition to apply to each element in the list
* @return a list of values which match the condition.
*/
public TLongList grep( TLongProcedure condition );
/**
* Searches the list for values which do <b>not</b> satisfy
* <tt>condition</tt>. This is akin to *nix <code>grep -v</code>.
*
* @param condition a condition to apply to each element in the list
* @return a list of values which do not match the condition.
*/
public TLongList inverseGrep( TLongProcedure condition );
/**
* Finds the maximum value in the list.
*
* @return the largest value in the list.
* @exception IllegalStateException if the list is empty
*/
public long max();
/**
* Finds the minimum value in the list.
*
* @return the smallest value in the list.
* @exception IllegalStateException if the list is empty
*/
public long min();
/**
* Calculates the sum of all the values in the list.
*
* @return the sum of the values in the list (zero if the list is empty).
*/
public long sum();
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list.array;
import gnu.trove.function.TLongFunction;
import gnu.trove.list.TLongList;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.iterator.TLongIterator;
import gnu.trove.TLongCollection;
import gnu.trove.impl.*;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* A resizable, array-backed list of long primitives.
*/
public class TLongArrayList implements TLongList, Externalizable {
static final long serialVersionUID = 1L;
/** the data of the list */
protected long[] _data;
/** the index after the last entry in the list */
protected int _pos;
/** the default capacity for new lists */
protected static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY;
/** the long value that represents null */
protected long no_entry_value;
/**
* Creates a new <code>TLongArrayList</code> instance with the
* default capacity.
*/
@SuppressWarnings({"RedundantCast"})
public TLongArrayList() {
this( DEFAULT_CAPACITY, ( long ) 0 );
}
/**
* Creates a new <code>TLongArrayList</code> instance with the
* specified capacity.
*
* @param capacity an <code>int</code> value
*/
@SuppressWarnings({"RedundantCast"})
public TLongArrayList( int capacity ) {
this( capacity, ( long ) 0 );
}
/**
* Creates a new <code>TLongArrayList</code> instance with the
* specified capacity.
*
* @param capacity an <code>int</code> value
* @param no_entry_value an <code>long</code> value that represents null.
*/
public TLongArrayList( int capacity, long no_entry_value ) {
_data = new long[ capacity ];
_pos = 0;
this.no_entry_value = no_entry_value;
}
/**
* Creates a new <code>TLongArrayList</code> instance that contains
* a copy of the collection passed to us.
*
* @param collection the collection to copy
*/
public TLongArrayList ( TLongCollection collection ) {
this( collection.size() );
addAll( collection );
}
/**
* Creates a new <code>TLongArrayList</code> instance whose
* capacity is the length of <tt>values</tt> array and whose
* initial contents are the specified values.
* <p>
* A defensive copy of the given values is held by the new instance.
*
* @param values an <code>long[]</code> value
*/
public TLongArrayList( long[] values ) {
this( values.length );
add( values );
}
protected TLongArrayList(long[] values, long no_entry_value, boolean wrap) {
if (!wrap)
throw new IllegalStateException("Wrong call");
if (values == null)
throw new IllegalArgumentException("values can not be null");
_data = values;
_pos = values.length;
this.no_entry_value = no_entry_value;
}
/**
* Returns a primitive List implementation that wraps around the given primitive array.
* <p/>
* NOTE: mutating operation are allowed as long as the List does not grow. In that case
* an IllegalStateException will be thrown
*
* @param values
* @return
*/
public static TLongArrayList wrap(long[] values) {
return wrap(values, ( long ) 0);
}
/**
* Returns a primitive List implementation that wraps around the given primitive array.
* <p/>
* NOTE: mutating operation are allowed as long as the List does not grow. In that case
* an IllegalStateException will be thrown
*
* @param values
* @param no_entry_value
* @return
*/
public static TLongArrayList wrap(long[] values, long no_entry_value) {
return new TLongArrayList(values, no_entry_value, true) {
/**
* Growing the wrapped external array is not allow
*/
@Override
public void ensureCapacity(int capacity) {
if (capacity > _data.length)
throw new IllegalStateException("Can not grow ArrayList wrapped external array");
}
};
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_value;
}
// sizing
/**
* Grow the internal array as needed to accommodate the specified number of elements.
* The size of the array bytes on each resize unless capacity requires more than twice
* the current capacity.
*/
public void ensureCapacity( int capacity ) {
if ( capacity > _data.length ) {
int newCap = Math.max( _data.length << 1, capacity );
long[] tmp = new long[ newCap ];
System.arraycopy( _data, 0, tmp, 0, _data.length );
_data = tmp;
}
}
/** {@inheritDoc} */
public int size() {
return _pos;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return _pos == 0;
}
/**
* Sheds any excess capacity above and beyond the current size of the list.
*/
public void trimToSize() {
if ( _data.length > size() ) {
long[] tmp = new long[ size() ];
toArray( tmp, 0, tmp.length );
_data = tmp;
}
}
// modifying
/** {@inheritDoc} */
public boolean add( long val ) {
ensureCapacity( _pos + 1 );
_data[ _pos++ ] = val;
return true;
}
/** {@inheritDoc} */
public void add( long[] vals ) {
add( vals, 0, vals.length );
}
/** {@inheritDoc} */
public void add( long[] vals, int offset, int length ) {
ensureCapacity( _pos + length );
System.arraycopy( vals, offset, _data, _pos, length );
_pos += length;
}
/** {@inheritDoc} */
public void insert( int offset, long value ) {
if ( offset == _pos ) {
add( value );
return;
}
ensureCapacity( _pos + 1 );
// shift right
System.arraycopy( _data, offset, _data, offset + 1, _pos - offset );
// insert
_data[ offset ] = value;
_pos++;
}
/** {@inheritDoc} */
public void insert( int offset, long[] values ) {
insert( offset, values, 0, values.length );
}
/** {@inheritDoc} */
public void insert( int offset, long[] values, int valOffset, int len ) {
if ( offset == _pos ) {
add( values, valOffset, len );
return;
}
ensureCapacity( _pos + len );
// shift right
System.arraycopy( _data, offset, _data, offset + len, _pos - offset );
// insert
System.arraycopy( values, valOffset, _data, offset, len );
_pos += len;
}
/** {@inheritDoc} */
public long get( int offset ) {
if ( offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
return _data[ offset ];
}
/**
* Returns the value at the specified offset without doing any bounds checking.
*/
public long getQuick( int offset ) {
return _data[ offset ];
}
/** {@inheritDoc} */
public long set( int offset, long val ) {
if ( offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
long prev_val = _data[ offset ];
_data[ offset ] = val;
return prev_val;
}
/** {@inheritDoc} */
public long replace( int offset, long val ) {
if ( offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
long old = _data[ offset ];
_data[ offset ] = val;
return old;
}
/** {@inheritDoc} */
public void set( int offset, long[] values ) {
set( offset, values, 0, values.length );
}
/** {@inheritDoc} */
public void set( int offset, long[] values, int valOffset, int length ) {
if ( offset < 0 || offset + length > _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
System.arraycopy( values, valOffset, _data, offset, length );
}
/**
* Sets the value at the specified offset without doing any bounds checking.
*/
public void setQuick( int offset, long val ) {
_data[ offset ] = val;
}
/** {@inheritDoc} */
public void clear() {
clear( DEFAULT_CAPACITY );
}
/**
* Flushes the internal state of the list, setting the capacity of the empty list to
* <tt>capacity</tt>.
*/
public void clear( int capacity ) {
_data = new long[ capacity ];
_pos = 0;
}
/**
* Sets the size of the list to 0, but does not change its capacity. This method can
* be used as an alternative to the {@link #clear()} method if you want to recycle a
* list without allocating new backing arrays.
*/
public void reset() {
_pos = 0;
Arrays.fill( _data, no_entry_value );
}
/**
* Sets the size of the list to 0, but does not change its capacity. This method can
* be used as an alternative to the {@link #clear()} method if you want to recycle a
* list without allocating new backing arrays. This method differs from
* {@link #reset()} in that it does not clear the old values in the backing array.
* Thus, it is possible for getQuick to return stale data if this method is used and
* the caller is careless about bounds checking.
*/
public void resetQuick() {
_pos = 0;
}
/** {@inheritDoc} */
public boolean remove( long value ) {
for ( int index = 0; index < _pos; index++ ) {
if ( value == _data[index] ) {
remove( index, 1 );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public long removeAt( int offset ) {
long old = get( offset );
remove( offset, 1 );
return old;
}
/** {@inheritDoc} */
public void remove( int offset, int length ) {
if ( length == 0 ) return;
if ( offset < 0 || offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException(offset);
}
if ( offset == 0 ) {
// data at the front
System.arraycopy( _data, length, _data, 0, _pos - length );
}
else if ( _pos - length == offset ) {
// no copy to make, decrementing pos "deletes" values at
// the end
}
else {
// data in the middle
System.arraycopy( _data, offset + length, _data, offset,
_pos - ( offset + length ) );
}
_pos -= length;
// no need to clear old values beyond _pos, because this is a
// primitive collection and 0 takes as much room as any other
// value
}
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongArrayIterator( 0 );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( ! contains( c ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
if ( this == collection ) {
return true;
}
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( ! contains( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( int i = array.length; i-- > 0; ) {
if ( ! contains( array[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Long> collection ) {
boolean changed = false;
for ( Long element : collection ) {
long e = element.longValue();
if ( add( e ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( TLongCollection collection ) {
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( add( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( long[] array ) {
boolean changed = false;
for ( long element : array ) {
if ( add( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] data = _data;
for ( int i = data.length; i-- > 0; ) {
if ( Arrays.binarySearch( array, data[i] ) < 0 ) {
remove( i, 1 );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( collection == this ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove(array[i]) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void transformValues( TLongFunction function ) {
for ( int i = _pos; i-- > 0; ) {
_data[ i ] = function.execute( _data[ i ] );
}
}
/** {@inheritDoc} */
public void reverse() {
reverse( 0, _pos );
}
/** {@inheritDoc} */
public void reverse( int from, int to ) {
if ( from == to ) {
return; // nothing to do
}
if ( from > to ) {
throw new IllegalArgumentException( "from cannot be greater than to" );
}
for ( int i = from, j = to - 1; i < j; i++, j-- ) {
swap( i, j );
}
}
/** {@inheritDoc} */
public void shuffle( Random rand ) {
for ( int i = _pos; i-- > 1; ) {
swap( i, rand.nextInt( i ) );
}
}
/**
* Swap the values at offsets <tt>i</tt> and <tt>j</tt>.
*
* @param i an offset into the data array
* @param j an offset into the data array
*/
private void swap( int i, int j ) {
long tmp = _data[ i ];
_data[ i ] = _data[ j ];
_data[ j ] = tmp;
}
// copying
/** {@inheritDoc} */
public TLongList subList( int begin, int end ) {
if ( end < begin ) {
throw new IllegalArgumentException( "end index " + end +
" greater than begin index " + begin );
}
if ( begin < 0 ) {
throw new IndexOutOfBoundsException( "begin index can not be < 0" );
}
if ( end > _data.length ) {
throw new IndexOutOfBoundsException( "end index < " + _data.length );
}
TLongArrayList list = new TLongArrayList( end - begin );
for ( int i = begin; i < end; i++ ) {
list.add( _data[ i ] );
}
return list;
}
/** {@inheritDoc} */
public long[] toArray() {
return toArray( 0, _pos );
}
/** {@inheritDoc} */
public long[] toArray( int offset, int len ) {
long[] rv = new long[ len ];
toArray( rv, offset, len );
return rv;
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
int len = dest.length;
if ( dest.length > _pos ) {
len = _pos;
dest[len] = no_entry_value;
}
toArray( dest, 0, len );
return dest;
}
/** {@inheritDoc} */
public long[] toArray( long[] dest, int offset, int len ) {
if ( len == 0 ) {
return dest; // nothing to copy
}
if ( offset < 0 || offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
System.arraycopy( _data, offset, dest, 0, len );
return dest;
}
/** {@inheritDoc} */
public long[] toArray( long[] dest, int source_pos, int dest_pos, int len ) {
if ( len == 0 ) {
return dest; // nothing to copy
}
if ( source_pos < 0 || source_pos >= _pos ) {
throw new ArrayIndexOutOfBoundsException( source_pos );
}
System.arraycopy( _data, source_pos, dest, dest_pos, len );
return dest;
}
// comparing
/** {@inheritDoc} */
@Override
public boolean equals( Object other ) {
if ( other == this ) {
return true;
}
else if ( other instanceof TLongArrayList ) {
TLongArrayList that = ( TLongArrayList )other;
if ( that.size() != this.size() ) return false;
else {
for ( int i = _pos; i-- > 0; ) {
if ( this._data[ i ] != that._data[ i ] ) {
return false;
}
}
return true;
}
}
else return false;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int h = 0;
for ( int i = _pos; i-- > 0; ) {
h += HashFunctions.hash( _data[ i ] );
}
return h;
}
// procedures
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
for ( int i = 0; i < _pos; i++ ) {
if ( !procedure.execute( _data[ i ] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean forEachDescending( TLongProcedure procedure ) {
for ( int i = _pos; i-- > 0; ) {
if ( !procedure.execute( _data[ i ] ) ) {
return false;
}
}
return true;
}
// sorting
/** {@inheritDoc} */
public void sort() {
Arrays.sort( _data, 0, _pos );
}
/** {@inheritDoc} */
public void sort( int fromIndex, int toIndex ) {
Arrays.sort( _data, fromIndex, toIndex );
}
// filling
/** {@inheritDoc} */
public void fill( long val ) {
Arrays.fill( _data, 0, _pos, val );
}
/** {@inheritDoc} */
public void fill( int fromIndex, int toIndex, long val ) {
if ( toIndex > _pos ) {
ensureCapacity( toIndex );
_pos = toIndex;
}
Arrays.fill( _data, fromIndex, toIndex, val );
}
// searching
/** {@inheritDoc} */
public int binarySearch( long value ) {
return binarySearch( value, 0, _pos );
}
/** {@inheritDoc} */
public int binarySearch(long value, int fromIndex, int toIndex) {
if ( fromIndex < 0 ) {
throw new ArrayIndexOutOfBoundsException( fromIndex );
}
if ( toIndex > _pos ) {
throw new ArrayIndexOutOfBoundsException( toIndex );
}
int low = fromIndex;
int high = toIndex - 1;
while ( low <= high ) {
int mid = ( low + high ) >>> 1;
long midVal = _data[ mid ];
if ( midVal < value ) {
low = mid + 1;
}
else if ( midVal > value ) {
high = mid - 1;
}
else {
return mid; // value found
}
}
return -( low + 1 ); // value not found.
}
/** {@inheritDoc} */
public int indexOf( long value ) {
return indexOf( 0, value );
}
/** {@inheritDoc} */
public int indexOf( int offset, long value ) {
for ( int i = offset; i < _pos; i++ ) {
if ( _data[ i ] == value ) {
return i;
}
}
return -1;
}
/** {@inheritDoc} */
public int lastIndexOf( long value ) {
return lastIndexOf( _pos, value );
}
/** {@inheritDoc} */
public int lastIndexOf( int offset, long value ) {
for ( int i = offset; i-- > 0; ) {
if ( _data[ i ] == value ) {
return i;
}
}
return -1;
}
/** {@inheritDoc} */
public boolean contains( long value ) {
return lastIndexOf( value ) >= 0;
}
/** {@inheritDoc} */
public TLongList grep( TLongProcedure condition ) {
TLongArrayList list = new TLongArrayList();
for ( int i = 0; i < _pos; i++ ) {
if ( condition.execute( _data[ i ] ) ) {
list.add( _data[ i ] );
}
}
return list;
}
/** {@inheritDoc} */
public TLongList inverseGrep( TLongProcedure condition ) {
TLongArrayList list = new TLongArrayList();
for ( int i = 0; i < _pos; i++ ) {
if ( !condition.execute( _data[ i ] ) ) {
list.add( _data[ i ] );
}
}
return list;
}
/** {@inheritDoc} */
public long max() {
if ( size() == 0 ) {
throw new IllegalStateException("cannot find maximum of an empty list");
}
long max = Long.MIN_VALUE;
for ( int i = 0; i < _pos; i++ ) {
if ( _data[ i ] > max ) {
max = _data[ i ];
}
}
return max;
}
/** {@inheritDoc} */
public long min() {
if ( size() == 0 ) {
throw new IllegalStateException( "cannot find minimum of an empty list" );
}
long min = Long.MAX_VALUE;
for ( int i = 0; i < _pos; i++ ) {
if ( _data[i] < min ) {
min = _data[i];
}
}
return min;
}
/** {@inheritDoc} */
public long sum() {
long sum = 0;
for ( int i = 0; i < _pos; i++ ) {
sum += _data[ i ];
}
return sum;
}
// stringification
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
for ( int i = 0, end = _pos - 1; i < end; i++ ) {
buf.append( _data[ i ] );
buf.append( ", " );
}
if ( size() > 0 ) {
buf.append( _data[ _pos - 1 ] );
}
buf.append( "}" );
return buf.toString();
}
/** TLongArrayList iterator */
class TLongArrayIterator implements TLongIterator {
/** Index of element to be returned by subsequent call to next. */
private int cursor = 0;
/**
* Index of element returned by most recent call to next or
* previous. Reset to -1 if this element is deleted by a call
* to remove.
*/
int lastRet = -1;
TLongArrayIterator( int index ) {
cursor = index;
}
/** {@inheritDoc} */
public boolean hasNext() {
return cursor < size();
}
/** {@inheritDoc} */
public long next() {
try {
long next = get( cursor );
lastRet = cursor++;
return next;
} catch ( IndexOutOfBoundsException e ) {
throw new NoSuchElementException();
}
}
/** {@inheritDoc} */
public void remove() {
if ( lastRet == -1 )
throw new IllegalStateException();
try {
TLongArrayList.this.remove( lastRet, 1);
if ( lastRet < cursor )
cursor--;
lastRet = -1;
} catch ( IndexOutOfBoundsException e ) {
throw new ConcurrentModificationException();
}
}
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// POSITION
out.writeInt( _pos );
// NO_ENTRY_VALUE
out.writeLong( no_entry_value );
// ENTRIES
int len = _data.length;
out.writeInt( len );
for( int i = 0; i < len; i++ ) {
out.writeLong( _data[ i ] );
}
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// POSITION
_pos = in.readInt();
// NO_ENTRY_VALUE
no_entry_value = in.readLong();
// ENTRIES
int len = in.readInt();
_data = new long[ len ];
for( int i = 0; i < len; i++ ) {
_data[ i ] = in.readLong();
}
}
} // TLongArrayList
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list.array;
import gnu.trove.function.TIntFunction;
import gnu.trove.list.TIntList;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.TIntCollection;
import gnu.trove.impl.*;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* A resizable, array-backed list of int primitives.
*/
public class TIntArrayList implements TIntList, Externalizable {
static final long serialVersionUID = 1L;
/** the data of the list */
protected int[] _data;
/** the index after the last entry in the list */
protected int _pos;
/** the default capacity for new lists */
protected static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY;
/** the int value that represents null */
protected int no_entry_value;
/**
* Creates a new <code>TIntArrayList</code> instance with the
* default capacity.
*/
@SuppressWarnings({"RedundantCast"})
public TIntArrayList() {
this( DEFAULT_CAPACITY, ( int ) 0 );
}
/**
* Creates a new <code>TIntArrayList</code> instance with the
* specified capacity.
*
* @param capacity an <code>int</code> value
*/
@SuppressWarnings({"RedundantCast"})
public TIntArrayList( int capacity ) {
this( capacity, ( int ) 0 );
}
/**
* Creates a new <code>TIntArrayList</code> instance with the
* specified capacity.
*
* @param capacity an <code>int</code> value
* @param no_entry_value an <code>int</code> value that represents null.
*/
public TIntArrayList( int capacity, int no_entry_value ) {
_data = new int[ capacity ];
_pos = 0;
this.no_entry_value = no_entry_value;
}
/**
* Creates a new <code>TIntArrayList</code> instance that contains
* a copy of the collection passed to us.
*
* @param collection the collection to copy
*/
public TIntArrayList ( TIntCollection collection ) {
this( collection.size() );
addAll( collection );
}
/**
* Creates a new <code>TIntArrayList</code> instance whose
* capacity is the length of <tt>values</tt> array and whose
* initial contents are the specified values.
* <p>
* A defensive copy of the given values is held by the new instance.
*
* @param values an <code>int[]</code> value
*/
public TIntArrayList( int[] values ) {
this( values.length );
add( values );
}
protected TIntArrayList(int[] values, int no_entry_value, boolean wrap) {
if (!wrap)
throw new IllegalStateException("Wrong call");
if (values == null)
throw new IllegalArgumentException("values can not be null");
_data = values;
_pos = values.length;
this.no_entry_value = no_entry_value;
}
/**
* Returns a primitive List implementation that wraps around the given primitive array.
* <p/>
* NOTE: mutating operation are allowed as long as the List does not grow. In that case
* an IllegalStateException will be thrown
*
* @param values
* @return
*/
public static TIntArrayList wrap(int[] values) {
return wrap(values, ( int ) 0);
}
/**
* Returns a primitive List implementation that wraps around the given primitive array.
* <p/>
* NOTE: mutating operation are allowed as long as the List does not grow. In that case
* an IllegalStateException will be thrown
*
* @param values
* @param no_entry_value
* @return
*/
public static TIntArrayList wrap(int[] values, int no_entry_value) {
return new TIntArrayList(values, no_entry_value, true) {
/**
* Growing the wrapped external array is not allow
*/
@Override
public void ensureCapacity(int capacity) {
if (capacity > _data.length)
throw new IllegalStateException("Can not grow ArrayList wrapped external array");
}
};
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_value;
}
// sizing
/**
* Grow the internal array as needed to accommodate the specified number of elements.
* The size of the array bytes on each resize unless capacity requires more than twice
* the current capacity.
*/
public void ensureCapacity( int capacity ) {
if ( capacity > _data.length ) {
int newCap = Math.max( _data.length << 1, capacity );
int[] tmp = new int[ newCap ];
System.arraycopy( _data, 0, tmp, 0, _data.length );
_data = tmp;
}
}
/** {@inheritDoc} */
public int size() {
return _pos;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return _pos == 0;
}
/**
* Sheds any excess capacity above and beyond the current size of the list.
*/
public void trimToSize() {
if ( _data.length > size() ) {
int[] tmp = new int[ size() ];
toArray( tmp, 0, tmp.length );
_data = tmp;
}
}
// modifying
/** {@inheritDoc} */
public boolean add( int val ) {
ensureCapacity( _pos + 1 );
_data[ _pos++ ] = val;
return true;
}
/** {@inheritDoc} */
public void add( int[] vals ) {
add( vals, 0, vals.length );
}
/** {@inheritDoc} */
public void add( int[] vals, int offset, int length ) {
ensureCapacity( _pos + length );
System.arraycopy( vals, offset, _data, _pos, length );
_pos += length;
}
/** {@inheritDoc} */
public void insert( int offset, int value ) {
if ( offset == _pos ) {
add( value );
return;
}
ensureCapacity( _pos + 1 );
// shift right
System.arraycopy( _data, offset, _data, offset + 1, _pos - offset );
// insert
_data[ offset ] = value;
_pos++;
}
/** {@inheritDoc} */
public void insert( int offset, int[] values ) {
insert( offset, values, 0, values.length );
}
/** {@inheritDoc} */
public void insert( int offset, int[] values, int valOffset, int len ) {
if ( offset == _pos ) {
add( values, valOffset, len );
return;
}
ensureCapacity( _pos + len );
// shift right
System.arraycopy( _data, offset, _data, offset + len, _pos - offset );
// insert
System.arraycopy( values, valOffset, _data, offset, len );
_pos += len;
}
/** {@inheritDoc} */
public int get( int offset ) {
if ( offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
return _data[ offset ];
}
/**
* Returns the value at the specified offset without doing any bounds checking.
*/
public int getQuick( int offset ) {
return _data[ offset ];
}
/** {@inheritDoc} */
public int set( int offset, int val ) {
if ( offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
int prev_val = _data[ offset ];
_data[ offset ] = val;
return prev_val;
}
/** {@inheritDoc} */
public int replace( int offset, int val ) {
if ( offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
int old = _data[ offset ];
_data[ offset ] = val;
return old;
}
/** {@inheritDoc} */
public void set( int offset, int[] values ) {
set( offset, values, 0, values.length );
}
/** {@inheritDoc} */
public void set( int offset, int[] values, int valOffset, int length ) {
if ( offset < 0 || offset + length > _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
System.arraycopy( values, valOffset, _data, offset, length );
}
/**
* Sets the value at the specified offset without doing any bounds checking.
*/
public void setQuick( int offset, int val ) {
_data[ offset ] = val;
}
/** {@inheritDoc} */
public void clear() {
clear( DEFAULT_CAPACITY );
}
/**
* Flushes the internal state of the list, setting the capacity of the empty list to
* <tt>capacity</tt>.
*/
public void clear( int capacity ) {
_data = new int[ capacity ];
_pos = 0;
}
/**
* Sets the size of the list to 0, but does not change its capacity. This method can
* be used as an alternative to the {@link #clear()} method if you want to recycle a
* list without allocating new backing arrays.
*/
public void reset() {
_pos = 0;
Arrays.fill( _data, no_entry_value );
}
/**
* Sets the size of the list to 0, but does not change its capacity. This method can
* be used as an alternative to the {@link #clear()} method if you want to recycle a
* list without allocating new backing arrays. This method differs from
* {@link #reset()} in that it does not clear the old values in the backing array.
* Thus, it is possible for getQuick to return stale data if this method is used and
* the caller is careless about bounds checking.
*/
public void resetQuick() {
_pos = 0;
}
/** {@inheritDoc} */
public boolean remove( int value ) {
for ( int index = 0; index < _pos; index++ ) {
if ( value == _data[index] ) {
remove( index, 1 );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public int removeAt( int offset ) {
int old = get( offset );
remove( offset, 1 );
return old;
}
/** {@inheritDoc} */
public void remove( int offset, int length ) {
if ( length == 0 ) return;
if ( offset < 0 || offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException(offset);
}
if ( offset == 0 ) {
// data at the front
System.arraycopy( _data, length, _data, 0, _pos - length );
}
else if ( _pos - length == offset ) {
// no copy to make, decrementing pos "deletes" values at
// the end
}
else {
// data in the middle
System.arraycopy( _data, offset + length, _data, offset,
_pos - ( offset + length ) );
}
_pos -= length;
// no need to clear old values beyond _pos, because this is a
// primitive collection and 0 takes as much room as any other
// value
}
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntArrayIterator( 0 );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( ! contains( c ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
if ( this == collection ) {
return true;
}
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( ! contains( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int i = array.length; i-- > 0; ) {
if ( ! contains( array[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Integer> collection ) {
boolean changed = false;
for ( Integer element : collection ) {
int e = element.intValue();
if ( add( e ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( TIntCollection collection ) {
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( add( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( int[] array ) {
boolean changed = false;
for ( int element : array ) {
if ( add( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] data = _data;
for ( int i = data.length; i-- > 0; ) {
if ( Arrays.binarySearch( array, data[i] ) < 0 ) {
remove( i, 1 );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( collection == this ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove(array[i]) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void transformValues( TIntFunction function ) {
for ( int i = _pos; i-- > 0; ) {
_data[ i ] = function.execute( _data[ i ] );
}
}
/** {@inheritDoc} */
public void reverse() {
reverse( 0, _pos );
}
/** {@inheritDoc} */
public void reverse( int from, int to ) {
if ( from == to ) {
return; // nothing to do
}
if ( from > to ) {
throw new IllegalArgumentException( "from cannot be greater than to" );
}
for ( int i = from, j = to - 1; i < j; i++, j-- ) {
swap( i, j );
}
}
/** {@inheritDoc} */
public void shuffle( Random rand ) {
for ( int i = _pos; i-- > 1; ) {
swap( i, rand.nextInt( i ) );
}
}
/**
* Swap the values at offsets <tt>i</tt> and <tt>j</tt>.
*
* @param i an offset into the data array
* @param j an offset into the data array
*/
private void swap( int i, int j ) {
int tmp = _data[ i ];
_data[ i ] = _data[ j ];
_data[ j ] = tmp;
}
// copying
/** {@inheritDoc} */
public TIntList subList( int begin, int end ) {
if ( end < begin ) {
throw new IllegalArgumentException( "end index " + end +
" greater than begin index " + begin );
}
if ( begin < 0 ) {
throw new IndexOutOfBoundsException( "begin index can not be < 0" );
}
if ( end > _data.length ) {
throw new IndexOutOfBoundsException( "end index < " + _data.length );
}
TIntArrayList list = new TIntArrayList( end - begin );
for ( int i = begin; i < end; i++ ) {
list.add( _data[ i ] );
}
return list;
}
/** {@inheritDoc} */
public int[] toArray() {
return toArray( 0, _pos );
}
/** {@inheritDoc} */
public int[] toArray( int offset, int len ) {
int[] rv = new int[ len ];
toArray( rv, offset, len );
return rv;
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
int len = dest.length;
if ( dest.length > _pos ) {
len = _pos;
dest[len] = no_entry_value;
}
toArray( dest, 0, len );
return dest;
}
/** {@inheritDoc} */
public int[] toArray( int[] dest, int offset, int len ) {
if ( len == 0 ) {
return dest; // nothing to copy
}
if ( offset < 0 || offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
System.arraycopy( _data, offset, dest, 0, len );
return dest;
}
/** {@inheritDoc} */
public int[] toArray( int[] dest, int source_pos, int dest_pos, int len ) {
if ( len == 0 ) {
return dest; // nothing to copy
}
if ( source_pos < 0 || source_pos >= _pos ) {
throw new ArrayIndexOutOfBoundsException( source_pos );
}
System.arraycopy( _data, source_pos, dest, dest_pos, len );
return dest;
}
// comparing
/** {@inheritDoc} */
@Override
public boolean equals( Object other ) {
if ( other == this ) {
return true;
}
else if ( other instanceof TIntArrayList ) {
TIntArrayList that = ( TIntArrayList )other;
if ( that.size() != this.size() ) return false;
else {
for ( int i = _pos; i-- > 0; ) {
if ( this._data[ i ] != that._data[ i ] ) {
return false;
}
}
return true;
}
}
else return false;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int h = 0;
for ( int i = _pos; i-- > 0; ) {
h += HashFunctions.hash( _data[ i ] );
}
return h;
}
// procedures
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
for ( int i = 0; i < _pos; i++ ) {
if ( !procedure.execute( _data[ i ] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean forEachDescending( TIntProcedure procedure ) {
for ( int i = _pos; i-- > 0; ) {
if ( !procedure.execute( _data[ i ] ) ) {
return false;
}
}
return true;
}
// sorting
/** {@inheritDoc} */
public void sort() {
Arrays.sort( _data, 0, _pos );
}
/** {@inheritDoc} */
public void sort( int fromIndex, int toIndex ) {
Arrays.sort( _data, fromIndex, toIndex );
}
// filling
/** {@inheritDoc} */
public void fill( int val ) {
Arrays.fill( _data, 0, _pos, val );
}
/** {@inheritDoc} */
public void fill( int fromIndex, int toIndex, int val ) {
if ( toIndex > _pos ) {
ensureCapacity( toIndex );
_pos = toIndex;
}
Arrays.fill( _data, fromIndex, toIndex, val );
}
// searching
/** {@inheritDoc} */
public int binarySearch( int value ) {
return binarySearch( value, 0, _pos );
}
/** {@inheritDoc} */
public int binarySearch(int value, int fromIndex, int toIndex) {
if ( fromIndex < 0 ) {
throw new ArrayIndexOutOfBoundsException( fromIndex );
}
if ( toIndex > _pos ) {
throw new ArrayIndexOutOfBoundsException( toIndex );
}
int low = fromIndex;
int high = toIndex - 1;
while ( low <= high ) {
int mid = ( low + high ) >>> 1;
int midVal = _data[ mid ];
if ( midVal < value ) {
low = mid + 1;
}
else if ( midVal > value ) {
high = mid - 1;
}
else {
return mid; // value found
}
}
return -( low + 1 ); // value not found.
}
/** {@inheritDoc} */
public int indexOf( int value ) {
return indexOf( 0, value );
}
/** {@inheritDoc} */
public int indexOf( int offset, int value ) {
for ( int i = offset; i < _pos; i++ ) {
if ( _data[ i ] == value ) {
return i;
}
}
return -1;
}
/** {@inheritDoc} */
public int lastIndexOf( int value ) {
return lastIndexOf( _pos, value );
}
/** {@inheritDoc} */
public int lastIndexOf( int offset, int value ) {
for ( int i = offset; i-- > 0; ) {
if ( _data[ i ] == value ) {
return i;
}
}
return -1;
}
/** {@inheritDoc} */
public boolean contains( int value ) {
return lastIndexOf( value ) >= 0;
}
/** {@inheritDoc} */
public TIntList grep( TIntProcedure condition ) {
TIntArrayList list = new TIntArrayList();
for ( int i = 0; i < _pos; i++ ) {
if ( condition.execute( _data[ i ] ) ) {
list.add( _data[ i ] );
}
}
return list;
}
/** {@inheritDoc} */
public TIntList inverseGrep( TIntProcedure condition ) {
TIntArrayList list = new TIntArrayList();
for ( int i = 0; i < _pos; i++ ) {
if ( !condition.execute( _data[ i ] ) ) {
list.add( _data[ i ] );
}
}
return list;
}
/** {@inheritDoc} */
public int max() {
if ( size() == 0 ) {
throw new IllegalStateException("cannot find maximum of an empty list");
}
int max = Integer.MIN_VALUE;
for ( int i = 0; i < _pos; i++ ) {
if ( _data[ i ] > max ) {
max = _data[ i ];
}
}
return max;
}
/** {@inheritDoc} */
public int min() {
if ( size() == 0 ) {
throw new IllegalStateException( "cannot find minimum of an empty list" );
}
int min = Integer.MAX_VALUE;
for ( int i = 0; i < _pos; i++ ) {
if ( _data[i] < min ) {
min = _data[i];
}
}
return min;
}
/** {@inheritDoc} */
public int sum() {
int sum = 0;
for ( int i = 0; i < _pos; i++ ) {
sum += _data[ i ];
}
return sum;
}
// stringification
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
for ( int i = 0, end = _pos - 1; i < end; i++ ) {
buf.append( _data[ i ] );
buf.append( ", " );
}
if ( size() > 0 ) {
buf.append( _data[ _pos - 1 ] );
}
buf.append( "}" );
return buf.toString();
}
/** TIntArrayList iterator */
class TIntArrayIterator implements TIntIterator {
/** Index of element to be returned by subsequent call to next. */
private int cursor = 0;
/**
* Index of element returned by most recent call to next or
* previous. Reset to -1 if this element is deleted by a call
* to remove.
*/
int lastRet = -1;
TIntArrayIterator( int index ) {
cursor = index;
}
/** {@inheritDoc} */
public boolean hasNext() {
return cursor < size();
}
/** {@inheritDoc} */
public int next() {
try {
int next = get( cursor );
lastRet = cursor++;
return next;
} catch ( IndexOutOfBoundsException e ) {
throw new NoSuchElementException();
}
}
/** {@inheritDoc} */
public void remove() {
if ( lastRet == -1 )
throw new IllegalStateException();
try {
TIntArrayList.this.remove( lastRet, 1);
if ( lastRet < cursor )
cursor--;
lastRet = -1;
} catch ( IndexOutOfBoundsException e ) {
throw new ConcurrentModificationException();
}
}
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// POSITION
out.writeInt( _pos );
// NO_ENTRY_VALUE
out.writeInt( no_entry_value );
// ENTRIES
int len = _data.length;
out.writeInt( len );
for( int i = 0; i < len; i++ ) {
out.writeInt( _data[ i ] );
}
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// POSITION
_pos = in.readInt();
// NO_ENTRY_VALUE
no_entry_value = in.readInt();
// ENTRIES
int len = in.readInt();
_data = new int[ len ];
for( int i = 0; i < len; i++ ) {
_data[ i ] = in.readInt();
}
}
} // TIntArrayList
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.function;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for functions that accept and return one long primitive.
*/
public interface TLongFunction {
/**
* Execute this function with <tt>value</tt>
*
* @param value a <code>long</code> input
* @return a <code>long</code> result
*/
public long execute( long value );
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.function;
/**
* Interface for functions that accept and return one Object reference.
* <p/>
* Created: Mon Nov 5 22:19:36 2001
*
* @author Eric D. Friedman
* @version $Id: TObjectFunction.java,v 1.1.2.1 2009/09/06 17:02:19 upholderoftruth Exp $
*/
public interface TObjectFunction<T, R> {
/**
* Execute this function with <tt>value</tt>
*
* @param value an <code>Object</code> input
* @return an <code>Object</code> result
*/
public R execute( T value );
}// TObjectFunction
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.function;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for functions that accept and return one int primitive.
*/
public interface TIntFunction {
/**
* Execute this function with <tt>value</tt>
*
* @param value a <code>int</code> input
* @return a <code>int</code> result
*/
public int execute( int value );
}
| Java |
// Copyright (c) 1999 CERN - European Organization for Nuclear Research.
// Permission to use, copy, modify, distribute and sell this software and
// its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and that
// both that copyright notice and this permission notice appear in
// supporting documentation. CERN makes no representations about the
// suitability of this software for any purpose. It is provided "as is"
// without expressed or implied warranty.
package gnu.trove.impl;
/**
* Provides various hash functions.
*
* @author wolfgang.hoschek@cern.ch
* @version 1.0, 09/24/99
*/
public final class HashFunctions {
/**
* Returns a hashcode for the specified value.
*
* @return a hash code value for the specified value.
*/
public static int hash(double value) {
assert !Double.isNaN(value) : "Values of NaN are not supported.";
long bits = Double.doubleToLongBits(value);
return (int)(bits ^ (bits >>> 32));
//return (int) Double.doubleToLongBits(value*663608941.737);
//this avoids excessive hashCollisions in the case values are
//of the form (1.0, 2.0, 3.0, ...)
}
/**
* Returns a hashcode for the specified value.
*
* @return a hash code value for the specified value.
*/
public static int hash(float value) {
assert !Float.isNaN(value) : "Values of NaN are not supported.";
return Float.floatToIntBits(value*663608941.737f);
// this avoids excessive hashCollisions in the case values are
// of the form (1.0, 2.0, 3.0, ...)
}
/**
* Returns a hashcode for the specified value.
*
* @return a hash code value for the specified value.
*/
public static int hash(int value) {
return value;
}
/**
* Returns a hashcode for the specified value.
*
* @return a hash code value for the specified value.
*/
public static int hash(long value) {
return ((int)(value ^ (value >>> 32)));
}
/**
* Returns a hashcode for the specified object.
*
* @return a hash code value for the specified object.
*/
public static int hash(Object object) {
return object==null ? 0 : object.hashCode();
}
/**
* In profiling, it has been found to be faster to have our own local implementation
* of "ceil" rather than to call to {@link Math#ceil(double)}.
*/
public static int fastCeil( float v ) {
int possible_result = ( int ) v;
if ( v - possible_result > 0 ) possible_result++;
return possible_result;
}
}
| Java |
// Copyright (c) 1999 CERN - European Organization for Nuclear Research.
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear in
// supporting documentation. CERN makes no representations about the
// suitability of this software for any purpose. It is provided "as is"
// without expressed or implied warranty.
package gnu.trove.impl;
import java.util.Arrays;
/*
* Modified for Trove to use the java.util.Arrays sort/search
* algorithms instead of those provided with colt.
*/
/**
* Used to keep hash table capacities prime numbers.
* Not of interest for users; only for implementors of hashtables.
*
* <p>Choosing prime numbers as hash table capacities is a good idea
* to keep them working fast, particularly under hash table
* expansions.
*
* <p>However, JDK 1.2, JGL 3.1 and many other toolkits do nothing to
* keep capacities prime. This class provides efficient means to
* choose prime capacities.
*
* <p>Choosing a prime is <tt>O(log 300)</tt> (binary search in a list
* of 300 ints). Memory requirements: 1 KB static memory.
*
* @author wolfgang.hoschek@cern.ch
* @version 1.0, 09/24/99
*/
public final class PrimeFinder {
/**
* The largest prime this class can generate; currently equal to
* <tt>Integer.MAX_VALUE</tt>.
*/
public static final int largestPrime = Integer.MAX_VALUE; //yes, it is prime.
/**
* The prime number list consists of 11 chunks.
*
* Each chunk contains prime numbers.
*
* A chunk starts with a prime P1. The next element is a prime
* P2. P2 is the smallest prime for which holds: P2 >= 2*P1.
*
* The next element is P3, for which the same holds with respect
* to P2, and so on.
*
* Chunks are chosen such that for any desired capacity >= 1000
* the list includes a prime number <= desired capacity * 1.11.
*
* Therefore, primes can be retrieved which are quite close to any
* desired capacity, which in turn avoids wasting memory.
*
* For example, the list includes
* 1039,1117,1201,1277,1361,1439,1523,1597,1759,1907,2081.
*
* So if you need a prime >= 1040, you will find a prime <=
* 1040*1.11=1154.
*
* Chunks are chosen such that they are optimized for a hashtable
* growthfactor of 2.0;
*
* If your hashtable has such a growthfactor then, after initially
* "rounding to a prime" upon hashtable construction, it will
* later expand to prime capacities such that there exist no
* better primes.
*
* In total these are about 32*10=320 numbers -> 1 KB of static
* memory needed.
*
* If you are stingy, then delete every second or fourth chunk.
*/
private static final int[] primeCapacities = {
//chunk #0
largestPrime,
//chunk #1
5,11,23,47,97,197,397,797,1597,3203,6421,12853,25717,51437,102877,205759,
411527,823117,1646237,3292489,6584983,13169977,26339969,52679969,105359939,
210719881,421439783,842879579,1685759167,
//chunk #2
433,877,1759,3527,7057,14143,28289,56591,113189,226379,452759,905551,1811107,
3622219,7244441,14488931,28977863,57955739,115911563,231823147,463646329,927292699,
1854585413,
//chunk #3
953,1907,3821,7643,15287,30577,61169,122347,244703,489407,978821,1957651,3915341,
7830701,15661423,31322867,62645741,125291483,250582987,501165979,1002331963,
2004663929,
//chunk #4
1039,2081,4177,8363,16729,33461,66923,133853,267713,535481,1070981,2141977,4283963,
8567929,17135863,34271747,68543509,137087021,274174111,548348231,1096696463,
//chunk #5
31,67,137,277,557,1117,2237,4481,8963,17929,35863,71741,143483,286973,573953,
1147921,2295859,4591721,9183457,18366923,36733847,73467739,146935499,293871013,
587742049,1175484103,
//chunk #6
599,1201,2411,4831,9677,19373,38747,77509,155027,310081,620171,1240361,2480729,
4961459,9922933,19845871,39691759,79383533,158767069,317534141,635068283,1270136683,
//chunk #7
311,631,1277,2557,5119,10243,20507,41017,82037,164089,328213,656429,1312867,
2625761,5251529,10503061,21006137,42012281,84024581,168049163,336098327,672196673,
1344393353,
//chunk #8
3,7,17,37,79,163,331,673,1361,2729,5471,10949,21911,43853,87719,175447,350899,
701819,1403641,2807303,5614657,11229331,22458671,44917381,89834777,179669557,
359339171,718678369,1437356741,
//chunk #9
43,89,179,359,719,1439,2879,5779,11579,23159,46327,92657,185323,370661,741337,
1482707,2965421,5930887,11861791,23723597,47447201,94894427,189788857,379577741,
759155483,1518310967,
//chunk #10
379,761,1523,3049,6101,12203,24407,48817,97649,195311,390647,781301,1562611,
3125257,6250537,12501169,25002389,50004791,100009607,200019221,400038451,800076929,
1600153859
};
static { //initializer
// The above prime numbers are formatted for human readability.
// To find numbers fast, we sort them once and for all.
Arrays.sort(primeCapacities);
}
/**
* Returns a prime number which is <code>>= desiredCapacity</code>
* and very close to <code>desiredCapacity</code> (within 11% if
* <code>desiredCapacity >= 1000</code>).
*
* @param desiredCapacity the capacity desired by the user.
* @return the capacity which should be used for a hashtable.
*/
public static final int nextPrime(int desiredCapacity) {
int i = Arrays.binarySearch(primeCapacities, desiredCapacity);
if (i<0) {
// desired capacity not found, choose next prime greater
// than desired capacity
i = -i -1; // remember the semantics of binarySearch...
}
return primeCapacities[i];
}
}
| Java |
// ////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// ////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl;
/**
* Central location for constants needed by various implementations.
*/
public class Constants {
private static final boolean VERBOSE =
System.getProperty( "gnu.trove.verbose", null ) != null;
/** the default capacity for new collections */
public static final int DEFAULT_CAPACITY = 10;
/** the load above which rehashing occurs. */
public static final float DEFAULT_LOAD_FACTOR = 0.5f;
/** the default value that represents for <tt>byte</tt> types. */
public static final byte DEFAULT_BYTE_NO_ENTRY_VALUE;
static {
byte value;
String property = System.getProperty( "gnu.trove.no_entry.byte", "0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Byte.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Byte.MIN_VALUE;
else value = Byte.valueOf( property );
if ( value > Byte.MAX_VALUE ) value = Byte.MAX_VALUE;
else if ( value < Byte.MIN_VALUE ) value = Byte.MIN_VALUE;
DEFAULT_BYTE_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_BYTE_NO_ENTRY_VALUE: " +
DEFAULT_BYTE_NO_ENTRY_VALUE );
}
}
/** the default value that represents for <tt>short</tt> types. */
public static final short DEFAULT_SHORT_NO_ENTRY_VALUE;
static {
short value;
String property = System.getProperty( "gnu.trove.no_entry.short", "0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Short.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Short.MIN_VALUE;
else value = Short.valueOf( property );
if ( value > Short.MAX_VALUE ) value = Short.MAX_VALUE;
else if ( value < Short.MIN_VALUE ) value = Short.MIN_VALUE;
DEFAULT_SHORT_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_SHORT_NO_ENTRY_VALUE: " +
DEFAULT_SHORT_NO_ENTRY_VALUE );
}
}
/** the default value that represents for <tt>char</tt> types. */
public static final char DEFAULT_CHAR_NO_ENTRY_VALUE;
static {
char value;
String property = System.getProperty( "gnu.trove.no_entry.char", "\0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Character.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Character.MIN_VALUE;
else value = property.toCharArray()[0];
if ( value > Character.MAX_VALUE ) value = Character.MAX_VALUE;
else if ( value < Character.MIN_VALUE ) value = Character.MIN_VALUE;
DEFAULT_CHAR_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_CHAR_NO_ENTRY_VALUE: " +
Integer.valueOf( value ) );
}
}
/** the default value that represents for <tt>int</tt> types. */
public static final int DEFAULT_INT_NO_ENTRY_VALUE;
static {
int value;
String property = System.getProperty( "gnu.trove.no_entry.int", "0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Integer.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Integer.MIN_VALUE;
else value = Integer.valueOf( property );
DEFAULT_INT_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_INT_NO_ENTRY_VALUE: " +
DEFAULT_INT_NO_ENTRY_VALUE );
}
}
/** the default value that represents for <tt>long</tt> types. */
public static final long DEFAULT_LONG_NO_ENTRY_VALUE;
static {
long value;
String property = System.getProperty( "gnu.trove.no_entry.long", "0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Long.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Long.MIN_VALUE;
else value = Long.valueOf( property );
DEFAULT_LONG_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_LONG_NO_ENTRY_VALUE: " +
DEFAULT_LONG_NO_ENTRY_VALUE );
}
}
/** the default value that represents for <tt>float</tt> types. */
public static final float DEFAULT_FLOAT_NO_ENTRY_VALUE;
static {
float value;
String property = System.getProperty( "gnu.trove.no_entry.float", "0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Float.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Float.MIN_VALUE;
// Value from Float.MIN_NORMAL (introduced in 1.6)
else if ( "MIN_NORMAL".equalsIgnoreCase( property ) ) value = 0x1.0p-126f;
else if ( "NEGATIVE_INFINITY".equalsIgnoreCase( property ) ) value = Float.NEGATIVE_INFINITY;
else if ( "POSITIVE_INFINITY".equalsIgnoreCase( property ) ) value = Float.POSITIVE_INFINITY;
// else if ( "NaN".equalsIgnoreCase( property ) ) value = Float.NaN;
else value = Float.valueOf( property );
DEFAULT_FLOAT_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_FLOAT_NO_ENTRY_VALUE: " +
DEFAULT_FLOAT_NO_ENTRY_VALUE );
}
}
/** the default value that represents for <tt>double</tt> types. */
public static final double DEFAULT_DOUBLE_NO_ENTRY_VALUE;
static {
double value;
String property = System.getProperty( "gnu.trove.no_entry.double", "0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Double.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Double.MIN_VALUE;
// Value from Double.MIN_NORMAL (introduced in 1.6)
else if ( "MIN_NORMAL".equalsIgnoreCase( property ) ) value = 0x1.0p-1022;
else if ( "NEGATIVE_INFINITY".equalsIgnoreCase( property ) ) value = Double.NEGATIVE_INFINITY;
else if ( "POSITIVE_INFINITY".equalsIgnoreCase( property ) ) value = Double.POSITIVE_INFINITY;
// else if ( "NaN".equalsIgnoreCase( property ) ) value = Double.NaN;
else value = Double.valueOf( property );
DEFAULT_DOUBLE_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_DOUBLE_NO_ENTRY_VALUE: " +
DEFAULT_DOUBLE_NO_ENTRY_VALUE );
}
}
}
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.iterator.TIterator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Implements all iterator functions for the hashed object set.
* Subclasses may override objectAtIndex to vary the object
* returned by calls to next() (e.g. for values, and Map.Entry
* objects).
* <p/>
* <p> Note that iteration is fastest if you forego the calls to
* <tt>hasNext</tt> in favor of checking the size of the structure
* yourself and then call next() that many times:
* <p/>
* <pre>
* Iterator i = collection.iterator();
* for (int size = collection.size(); size-- > 0;) {
* Object o = i.next();
* }
* </pre>
* <p/>
* <p>You may, of course, use the hasNext(), next() idiom too if
* you aren't in a performance critical spot.</p>
*/
public abstract class THashIterator<V> implements TIterator, Iterator<V> {
private final TObjectHash<V> _object_hash;
/** the data structure this iterator traverses */
protected final THash _hash;
/**
* the number of elements this iterator believes are in the
* data structure it accesses.
*/
protected int _expectedSize;
/** the index used for iteration. */
protected int _index;
/**
* Create an instance of THashIterator over the values of the TObjectHash
*
* @param hash the object
*/
protected THashIterator( TObjectHash<V> hash ) {
_hash = hash;
_expectedSize = _hash.size();
_index = _hash.capacity();
_object_hash = hash;
}
/**
* Moves the iterator to the next Object and returns it.
*
* @return an <code>Object</code> value
* @throws ConcurrentModificationException
* if the structure
* was changed using a method that isn't on this iterator.
* @throws NoSuchElementException if this is called on an
* exhausted iterator.
*/
public V next() {
moveToNextIndex();
return objectAtIndex( _index );
}
/**
* Returns true if the iterator can be advanced past its current
* location.
*
* @return a <code>boolean</code> value
*/
public boolean hasNext() {
return nextIndex() >= 0;
}
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
/**
* Sets the internal <tt>index</tt> so that the `next' object
* can be returned.
*/
protected final void moveToNextIndex() {
// doing the assignment && < 0 in one line shaves
// 3 opcodes...
if ( ( _index = nextIndex() ) < 0 ) {
throw new NoSuchElementException();
}
}
/**
* Returns the index of the next value in the data structure
* or a negative value if the iterator is exhausted.
*
* @return an <code>int</code> value
* @throws ConcurrentModificationException
* if the underlying
* collection's size has been modified since the iterator was
* created.
*/
protected final int nextIndex() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
Object[] set = _object_hash._set;
int i = _index;
while ( i-- > 0 && ( set[i] == TObjectHash.FREE || set[i] == TObjectHash.REMOVED ) ) {
;
}
return i;
}
/**
* Returns the object at the specified index. Subclasses should
* implement this to return the appropriate object for the given
* index.
*
* @param index the index of the value to return.
* @return an <code>Object</code> value
*/
abstract protected V objectAtIndex( int index );
} // THashIterator
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.Constants;
import java.util.Arrays;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed hashing implementation for int primitives.
*
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman, Rob Eden, Jeff Randall
* @version $Id: _E_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TIntHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of ints */
public transient int[] _set;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected int no_entry_value;
protected boolean consumeFreeSlot;
/**
* Creates a new <code>TIntHash</code> instance with the default
* capacity and load factor.
*/
public TIntHash() {
super();
no_entry_value = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TIntHash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntHash( int initialCapacity ) {
super( initialCapacity );
no_entry_value = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TIntHash( int initialCapacity, float loadFactor ) {
super(initialCapacity, loadFactor);
no_entry_value = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TIntHash( int initialCapacity, float loadFactor, int no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_value = no_entry_value;
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryValue() {
return no_entry_value;
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_set = new int[capacity];
return capacity;
}
/**
* Searches the set for <tt>val</tt>
*
* @param val an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( int val ) {
return index(val) >= 0;
}
/**
* Executes <tt>procedure</tt> for each element in the set.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
public boolean forEach( TIntProcedure procedure ) {
byte[] states = _states;
int[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( set[i] ) ) {
return false;
}
}
return true;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_set[index] = no_entry_value;
super.removeAt( index );
}
/**
* Locates the index of <tt>val</tt>.
*
* @param val an <code>int</code> value
* @return the index of <tt>val</tt> or -1 if it isn't in the set.
*/
protected int index( int val ) {
int hash, probe, index, length;
final byte[] states = _states;
final int[] set = _set;
length = states.length;
hash = HashFunctions.hash( val ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == val)
return index;
return indexRehashed(val, index, hash, state);
}
int indexRehashed(int key, int index, int hash, byte state) {
// see Knuth, p. 529
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
//
if (state == FREE)
return -1;
//
if (key == _set[index])
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>val</tt> can be inserted. if
* there is already a value equal()ing <tt>val</tt> in the set,
* returns that value as a negative integer.
*
* @param val an <code>int</code> value
* @return an <code>int</code> value
*/
protected int insertKey( int val ) {
int hash, index;
hash = HashFunctions.hash(val) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index; // empty, all done
}
if (state == FULL && _set[index] == val) {
return -index - 1; // already stored
}
// already FULL or REMOVED, must probe
return insertKeyRehash(val, index, hash, state);
}
int insertKeyRehash(int val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, int val) {
_set[index] = val; // insert value
_states[index] = FULL;
}
} // TIntHash
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.impl.HashFunctions;
/**
* The base class for hashtables of primitive values. Since there is
* no notion of object equality for primitives, it isn't possible to
* use a `REMOVED' object to track deletions in an open-addressed table.
* So, we have to resort to using a parallel `bookkeeping' array of bytes,
* in which flags can be set to indicate that a particular slot in the
* hash table is FREE, FULL, or REMOVED.
*
* @author Eric D. Friedman, Rob Eden, Jeff Randall
* @version $Id: TPrimitiveHash.java,v 1.1.2.6 2010/03/01 23:39:07 robeden Exp $
*/
abstract public class TPrimitiveHash extends THash {
@SuppressWarnings( { "UnusedDeclaration" } )
static final long serialVersionUID = 1L;
/**
* flags indicating whether each position in the hash is
* FREE, FULL, or REMOVED
*/
public transient byte[] _states;
/* constants used for state flags */
/** flag indicating that a slot in the hashtable is available */
public static final byte FREE = 0;
/** flag indicating that a slot in the hashtable is occupied */
public static final byte FULL = 1;
/**
* flag indicating that the value of a slot in the hashtable
* was deleted
*/
public static final byte REMOVED = 2;
/**
* Creates a new <code>THash</code> instance with the default
* capacity and load factor.
*/
public TPrimitiveHash() {
super();
}
/**
* Creates a new <code>TPrimitiveHash</code> instance with a prime
* capacity at or near the specified capacity and with the default
* load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TPrimitiveHash( int initialCapacity ) {
this( initialCapacity, DEFAULT_LOAD_FACTOR );
}
/**
* Creates a new <code>TPrimitiveHash</code> instance with a prime
* capacity at or near the minimum needed to hold
* <tt>initialCapacity<tt> elements with load factor
* <tt>loadFactor</tt> without triggering a rehash.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TPrimitiveHash( int initialCapacity, float loadFactor ) {
super();
initialCapacity = Math.max( 1, initialCapacity );
_loadFactor = loadFactor;
setUp( HashFunctions.fastCeil( initialCapacity / loadFactor ) );
}
/**
* Returns the capacity of the hash table. This is the true
* physical capacity, without adjusting for the load factor.
*
* @return the physical capacity of the hash table.
*/
public int capacity() {
return _states.length;
}
/**
* Delete the record at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_states[index] = REMOVED;
super.removeAt( index );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_states = new byte[capacity];
return capacity;
}
} // TPrimitiveHash | Java |
// ////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// ////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.iterator.TPrimitiveIterator;
import java.util.ConcurrentModificationException;
import java.util.NoSuchElementException;
/**
* Implements all iterator functions for the hashed object set.
* Subclasses may override objectAtIndex to vary the object
* returned by calls to next() (e.g. for values, and Map.Entry
* objects).
* <p/>
* <p> Note that iteration is fastest if you forego the calls to
* <tt>hasNext</tt> in favor of checking the size of the structure
* yourself and then call next() that many times:
* <p/>
* <pre>
* Iterator i = collection.iterator();
* for (int size = collection.size(); size-- > 0;) {
* Object o = i.next();
* }
* </pre>
* <p/>
* <p>You may, of course, use the hasNext(), next() idiom too if
* you aren't in a performance critical spot.</p>
*/
public abstract class THashPrimitiveIterator implements TPrimitiveIterator {
/** the data structure this iterator traverses */
protected final TPrimitiveHash _hash;
/**
* the number of elements this iterator believes are in the
* data structure it accesses.
*/
protected int _expectedSize;
/** the index used for iteration. */
protected int _index;
/**
* Creates a <tt>TPrimitiveIterator</tt> for the specified collection.
*
* @param hash the <tt>TPrimitiveHash</tt> we want to iterate over.
*/
public THashPrimitiveIterator( TPrimitiveHash hash ) {
_hash = hash;
_expectedSize = _hash.size();
_index = _hash.capacity();
}
/**
* Returns the index of the next value in the data structure
* or a negative value if the iterator is exhausted.
*
* @return an <code>int</code> value
* @throws java.util.ConcurrentModificationException
* if the underlying collection's
* size has been modified since the iterator was created.
*/
protected final int nextIndex() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
byte[] states = _hash._states;
int i = _index;
while ( i-- > 0 && ( states[i] != TPrimitiveHash.FULL ) ) {
;
}
return i;
}
/**
* Returns true if the iterator can be advanced past its current
* location.
*
* @return a <code>boolean</code> value
*/
public boolean hasNext() {
return nextIndex() >= 0;
}
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if (_expectedSize != _hash.size()) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt(_index);
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
/**
* Sets the internal <tt>index</tt> so that the `next' object
* can be returned.
*/
protected final void moveToNextIndex() {
// doing the assignment && < 0 in one line shaves
// 3 opcodes...
if ( ( _index = nextIndex() ) < 0 ) {
throw new NoSuchElementException();
}
}
} // TPrimitiveIterator | Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.*;
import gnu.trove.impl.HashFunctions;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed hashing implementation for int/int primitive entries.
*
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TIntIntHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of ints */
public transient int[] _set;
/**
* key that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected int no_entry_key;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected int no_entry_value;
protected boolean consumeFreeSlot;
/**
* Creates a new <code>T#E#Hash</code> instance with the default
* capacity and load factor.
*/
public TIntIntHash() {
super();
no_entry_key = ( int ) 0;
no_entry_value = ( int ) 0;
}
/**
* Creates a new <code>T#E#Hash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntIntHash( int initialCapacity ) {
super( initialCapacity );
no_entry_key = ( int ) 0;
no_entry_value = ( int ) 0;
}
/**
* Creates a new <code>TIntIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TIntIntHash( int initialCapacity, float loadFactor ) {
super(initialCapacity, loadFactor);
no_entry_key = ( int ) 0;
no_entry_value = ( int ) 0;
}
/**
* Creates a new <code>TIntIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TIntIntHash( int initialCapacity, float loadFactor,
int no_entry_key, int no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_key = no_entry_key;
this.no_entry_value = no_entry_value;
}
/**
* Returns the value that is used to represent null as a key. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryKey() {
return no_entry_key;
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryValue() {
return no_entry_value;
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_set = new int[capacity];
return capacity;
}
/**
* Searches the set for <tt>val</tt>
*
* @param val an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( int val ) {
return index(val) >= 0;
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
public boolean forEach( TIntProcedure procedure ) {
byte[] states = _states;
int[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( set[i] ) ) {
return false;
}
}
return true;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_set[index] = no_entry_key;
super.removeAt( index );
}
/**
* Locates the index of <tt>val</tt>.
*
* @param key an <code>int</code> value
* @return the index of <tt>val</tt> or -1 if it isn't in the set.
*/
protected int index( int key ) {
int hash, probe, index, length;
final byte[] states = _states;
final int[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == key)
return index;
return indexRehashed(key, index, hash, state);
}
int indexRehashed(int key, int index, int hash, byte state) {
// see Knuth, p. 529
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
//
if (state == FREE)
return -1;
//
if (key == _set[index])
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>val</tt> can be inserted. if
* there is already a value equal()ing <tt>val</tt> in the set,
* returns that value as a negative integer.
*
* @param key an <code>int</code> value
* @return an <code>int</code> value
*/
protected int insertKey( int val ) {
int hash, index;
hash = HashFunctions.hash(val) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index; // empty, all done
}
if (state == FULL && _set[index] == val) {
return -index - 1; // already stored
}
// already FULL or REMOVED, must probe
return insertKeyRehash(val, index, hash, state);
}
int insertKeyRehash(int val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, int val) {
_set[index] = val; // insert value
_states[index] = FULL;
}
protected int XinsertKey( int key ) {
int hash, probe, index, length;
final byte[] states = _states;
final int[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
consumeFreeSlot = false;
if ( state == FREE ) {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index; // empty, all done
} else if ( state == FULL && set[index] == key ) {
return -index -1; // already stored
} else { // already FULL or REMOVED, must probe
// compute the double hash
probe = 1 + ( hash % ( length - 2 ) );
// if the slot we landed on is FULL (but not removed), probe
// until we find an empty slot, a REMOVED slot, or an element
// equal to the one we are trying to insert.
// finding an empty slot means that the value is not present
// and that we should use that slot as the insertion point;
// finding a REMOVED slot means that we need to keep searching,
// however we want to remember the offset of that REMOVED slot
// so we can reuse it in case a "new" insertion (i.e. not an update)
// is possible.
// finding a matching value means that we've found that our desired
// key is already in the table
if ( state != REMOVED ) {
// starting at the natural offset, probe until we find an
// offset that isn't full.
do {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
} while ( state == FULL && set[index] != key );
}
// if the index we found was removed: continue probing until we
// locate a free location or an element which equal()s the
// one we have.
if ( state == REMOVED) {
int firstRemoved = index;
while ( state != FREE && ( state == REMOVED || set[index] != key ) ) {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
}
if (state == FULL) {
return -index -1;
} else {
set[index] = key;
states[index] = FULL;
return firstRemoved;
}
}
// if it's full, the key is already stored
if (state == FULL) {
return -index -1;
} else {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index;
}
}
}
/** {@inheritDoc} */
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeInt( no_entry_key );
// NO_ENTRY_VALUE
out.writeInt( no_entry_value );
}
/** {@inheritDoc} */
public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readInt();
// NO_ENTRY_VALUE
no_entry_value = in.readInt();
}
} // TIntIntHash
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.impl.Constants;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.PrimeFinder;
import java.io.Externalizable;
import java.io.ObjectOutput;
import java.io.IOException;
import java.io.ObjectInput;
/**
* Base class for hashtables that use open addressing to resolve
* collisions.
*
* Created: Wed Nov 28 21:11:16 2001
*
* @author Eric D. Friedman
* @author Rob Eden (auto-compaction)
* @author Jeff Randall
*
* @version $Id: THash.java,v 1.1.2.4 2010/03/02 00:55:34 robeden Exp $
*/
abstract public class THash implements Externalizable {
@SuppressWarnings( { "UnusedDeclaration" } )
static final long serialVersionUID = -1792948471915530295L;
/** the load above which rehashing occurs. */
protected static final float DEFAULT_LOAD_FACTOR = Constants.DEFAULT_LOAD_FACTOR;
/**
* the default initial capacity for the hash table. This is one
* less than a prime value because one is added to it when
* searching for a prime capacity to account for the free slot
* required by open addressing. Thus, the real default capacity is
* 11.
*/
protected static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY;
/** the current number of occupied slots in the hash. */
protected transient int _size;
/** the current number of free slots in the hash. */
protected transient int _free;
/**
* Determines how full the internal table can become before
* rehashing is required. This must be a value in the range: 0.0 <
* loadFactor < 1.0. The default value is 0.5, which is about as
* large as you can get in open addressing without hurting
* performance. Cf. Knuth, Volume 3., Chapter 6.
*/
protected float _loadFactor;
/**
* The maximum number of elements allowed without allocating more
* space.
*/
protected int _maxSize;
/** The number of removes that should be performed before an auto-compaction occurs. */
protected int _autoCompactRemovesRemaining;
/**
* The auto-compaction factor for the table.
*
* @see #setAutoCompactionFactor
*/
protected float _autoCompactionFactor;
/** @see #tempDisableAutoCompaction */
protected transient boolean _autoCompactTemporaryDisable = false;
/**
* Creates a new <code>THash</code> instance with the default
* capacity and load factor.
*/
public THash() {
this( DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR );
}
/**
* Creates a new <code>THash</code> instance with a prime capacity
* at or near the specified capacity and with the default load
* factor.
*
* @param initialCapacity an <code>int</code> value
*/
public THash( int initialCapacity ) {
this( initialCapacity, DEFAULT_LOAD_FACTOR );
}
/**
* Creates a new <code>THash</code> instance with a prime capacity
* at or near the minimum needed to hold <tt>initialCapacity</tt>
* elements with load factor <tt>loadFactor</tt> without triggering
* a rehash.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public THash( int initialCapacity, float loadFactor ) {
super();
_loadFactor = loadFactor;
// Through testing, the load factor (especially the default load factor) has been
// found to be a pretty good starting auto-compaction factor.
_autoCompactionFactor = loadFactor;
setUp( HashFunctions.fastCeil( initialCapacity / loadFactor ) );
}
/**
* Tells whether this set is currently holding any elements.
*
* @return a <code>boolean</code> value
*/
public boolean isEmpty() {
return 0 == _size;
}
/**
* Returns the number of distinct elements in this collection.
*
* @return an <code>int</code> value
*/
public int size() {
return _size;
}
/** @return the current physical capacity of the hash table. */
abstract public int capacity();
/**
* Ensure that this hashtable has sufficient capacity to hold
* <tt>desiredCapacity<tt> <b>additional</b> elements without
* requiring a rehash. This is a tuning method you can call
* before doing a large insert.
*
* @param desiredCapacity an <code>int</code> value
*/
public void ensureCapacity( int desiredCapacity ) {
if ( desiredCapacity > ( _maxSize - size() ) ) {
rehash( PrimeFinder.nextPrime( Math.max( size() + 1,
HashFunctions.fastCeil( ( desiredCapacity + size() ) / _loadFactor ) + 1 ) ) );
computeMaxSize( capacity() );
}
}
/**
* Compresses the hashtable to the minimum prime size (as defined
* by PrimeFinder) that will hold all of the elements currently in
* the table. If you have done a lot of <tt>remove</tt>
* operations and plan to do a lot of queries or insertions or
* iteration, it is a good idea to invoke this method. Doing so
* will accomplish two things:
* <p/>
* <ol>
* <li> You'll free memory allocated to the table but no
* longer needed because of the remove()s.</li>
* <p/>
* <li> You'll get better query/insert/iterator performance
* because there won't be any <tt>REMOVED</tt> slots to skip
* over when probing for indices in the table.</li>
* </ol>
*/
public void compact() {
// need at least one free spot for open addressing
rehash( PrimeFinder.nextPrime( Math.max( _size + 1,
HashFunctions.fastCeil( size() / _loadFactor ) + 1 ) ) );
computeMaxSize( capacity() );
// If auto-compaction is enabled, re-determine the compaction interval
if ( _autoCompactionFactor != 0 ) {
computeNextAutoCompactionAmount( size() );
}
}
/**
* The auto-compaction factor controls whether and when a table performs a
* {@link #compact} automatically after a certain number of remove operations.
* If the value is non-zero, the number of removes that need to occur for
* auto-compaction is the size of table at the time of the previous compaction
* (or the initial capacity) multiplied by this factor.
* <p/>
* Setting this value to zero will disable auto-compaction.
*
* @param factor a <tt>float</tt> that indicates the auto-compaction factor
*/
public void setAutoCompactionFactor( float factor ) {
if ( factor < 0 ) {
throw new IllegalArgumentException( "Factor must be >= 0: " + factor );
}
_autoCompactionFactor = factor;
}
/**
* @see #setAutoCompactionFactor
*
* @return a <<tt>float</tt> that represents the auto-compaction factor.
*/
public float getAutoCompactionFactor() {
return _autoCompactionFactor;
}
/**
* This simply calls {@link #compact compact}. It is included for
* symmetry with other collection classes. Note that the name of this
* method is somewhat misleading (which is why we prefer
* <tt>compact</tt>) as the load factor may require capacity above
* and beyond the size of this collection.
*
* @see #compact
*/
public final void trimToSize() {
compact();
}
/**
* Delete the record at <tt>index</tt>. Reduces the size of the
* collection by one.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_size--;
// If auto-compaction is enabled, see if we need to compact
if ( _autoCompactionFactor != 0 ) {
_autoCompactRemovesRemaining--;
if ( !_autoCompactTemporaryDisable && _autoCompactRemovesRemaining <= 0 ) {
// Do the compact
// NOTE: this will cause the next compaction interval to be calculated
compact();
}
}
}
/** Empties the collection. */
public void clear() {
_size = 0;
_free = capacity();
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = PrimeFinder.nextPrime( initialCapacity );
computeMaxSize( capacity );
computeNextAutoCompactionAmount( initialCapacity );
return capacity;
}
/**
* Rehashes the set.
*
* @param newCapacity an <code>int</code> value
*/
protected abstract void rehash( int newCapacity );
/**
* Temporarily disables auto-compaction. MUST be followed by calling
* {@link #reenableAutoCompaction}.
*/
public void tempDisableAutoCompaction() {
_autoCompactTemporaryDisable = true;
}
/**
* Re-enable auto-compaction after it was disabled via
* {@link #tempDisableAutoCompaction()}.
*
* @param check_for_compaction True if compaction should be performed if needed
* before returning. If false, no compaction will be
* performed.
*/
public void reenableAutoCompaction( boolean check_for_compaction ) {
_autoCompactTemporaryDisable = false;
if ( check_for_compaction && _autoCompactRemovesRemaining <= 0 &&
_autoCompactionFactor != 0 ) {
// Do the compact
// NOTE: this will cause the next compaction interval to be calculated
compact();
}
}
/**
* Computes the values of maxSize. There will always be at least
* one free slot required.
*
* @param capacity an <code>int</code> value
*/
protected void computeMaxSize( int capacity ) {
// need at least one free slot for open addressing
_maxSize = Math.min( capacity - 1, (int) ( capacity * _loadFactor ) );
_free = capacity - _size; // reset the free element count
}
/**
* Computes the number of removes that need to happen before the next auto-compaction
* will occur.
*
* @param size an <tt>int</tt> that sets the auto-compaction limit.
*/
protected void computeNextAutoCompactionAmount( int size ) {
if ( _autoCompactionFactor != 0 ) {
// NOTE: doing the round ourselves has been found to be faster than using
// Math.round.
_autoCompactRemovesRemaining =
(int) ( ( size * _autoCompactionFactor ) + 0.5f );
}
}
/**
* After an insert, this hook is called to adjust the size/free
* values of the set and to perform rehashing if necessary.
*
* @param usedFreeSlot the slot
*/
protected final void postInsertHook( boolean usedFreeSlot ) {
if ( usedFreeSlot ) {
_free--;
}
// rehash whenever we exhaust the available space in the table
if ( ++_size > _maxSize || _free == 0 ) {
// choose a new capacity suited to the new state of the table
// if we've grown beyond our maximum size, double capacity;
// if we've exhausted the free spots, rehash to the same capacity,
// which will free up any stale removed slots for reuse.
int newCapacity = _size > _maxSize ? PrimeFinder.nextPrime( capacity() << 1 ) : capacity();
rehash( newCapacity );
computeMaxSize( capacity() );
}
}
protected int calculateGrownCapacity() {
return capacity() << 1;
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// LOAD FACTOR
out.writeFloat( _loadFactor );
// AUTO COMPACTION LOAD FACTOR
out.writeFloat( _autoCompactionFactor );
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// LOAD FACTOR
float old_factor = _loadFactor;
_loadFactor = in.readFloat();
// AUTO COMPACTION LOAD FACTOR
_autoCompactionFactor = in.readFloat();
// If we change the laod factor from the default, re-setup
if ( old_factor != _loadFactor ) {
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
}
}// THash | Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.*;
import gnu.trove.impl.HashFunctions;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed hashing implementation for int/long primitive entries.
*
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TIntLongHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of ints */
public transient int[] _set;
/**
* key that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected int no_entry_key;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected long no_entry_value;
protected boolean consumeFreeSlot;
/**
* Creates a new <code>T#E#Hash</code> instance with the default
* capacity and load factor.
*/
public TIntLongHash() {
super();
no_entry_key = ( int ) 0;
no_entry_value = ( long ) 0;
}
/**
* Creates a new <code>T#E#Hash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntLongHash( int initialCapacity ) {
super( initialCapacity );
no_entry_key = ( int ) 0;
no_entry_value = ( long ) 0;
}
/**
* Creates a new <code>TIntLongHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TIntLongHash( int initialCapacity, float loadFactor ) {
super(initialCapacity, loadFactor);
no_entry_key = ( int ) 0;
no_entry_value = ( long ) 0;
}
/**
* Creates a new <code>TIntLongHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TIntLongHash( int initialCapacity, float loadFactor,
int no_entry_key, long no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_key = no_entry_key;
this.no_entry_value = no_entry_value;
}
/**
* Returns the value that is used to represent null as a key. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryKey() {
return no_entry_key;
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryValue() {
return no_entry_value;
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_set = new int[capacity];
return capacity;
}
/**
* Searches the set for <tt>val</tt>
*
* @param val an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( int val ) {
return index(val) >= 0;
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
public boolean forEach( TIntProcedure procedure ) {
byte[] states = _states;
int[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( set[i] ) ) {
return false;
}
}
return true;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_set[index] = no_entry_key;
super.removeAt( index );
}
/**
* Locates the index of <tt>val</tt>.
*
* @param key an <code>int</code> value
* @return the index of <tt>val</tt> or -1 if it isn't in the set.
*/
protected int index( int key ) {
int hash, probe, index, length;
final byte[] states = _states;
final int[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == key)
return index;
return indexRehashed(key, index, hash, state);
}
int indexRehashed(int key, int index, int hash, byte state) {
// see Knuth, p. 529
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
//
if (state == FREE)
return -1;
//
if (key == _set[index])
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>val</tt> can be inserted. if
* there is already a value equal()ing <tt>val</tt> in the set,
* returns that value as a negative integer.
*
* @param key an <code>int</code> value
* @return an <code>int</code> value
*/
protected int insertKey( int val ) {
int hash, index;
hash = HashFunctions.hash(val) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index; // empty, all done
}
if (state == FULL && _set[index] == val) {
return -index - 1; // already stored
}
// already FULL or REMOVED, must probe
return insertKeyRehash(val, index, hash, state);
}
int insertKeyRehash(int val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, int val) {
_set[index] = val; // insert value
_states[index] = FULL;
}
protected int XinsertKey( int key ) {
int hash, probe, index, length;
final byte[] states = _states;
final int[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
consumeFreeSlot = false;
if ( state == FREE ) {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index; // empty, all done
} else if ( state == FULL && set[index] == key ) {
return -index -1; // already stored
} else { // already FULL or REMOVED, must probe
// compute the double hash
probe = 1 + ( hash % ( length - 2 ) );
// if the slot we landed on is FULL (but not removed), probe
// until we find an empty slot, a REMOVED slot, or an element
// equal to the one we are trying to insert.
// finding an empty slot means that the value is not present
// and that we should use that slot as the insertion point;
// finding a REMOVED slot means that we need to keep searching,
// however we want to remember the offset of that REMOVED slot
// so we can reuse it in case a "new" insertion (i.e. not an update)
// is possible.
// finding a matching value means that we've found that our desired
// key is already in the table
if ( state != REMOVED ) {
// starting at the natural offset, probe until we find an
// offset that isn't full.
do {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
} while ( state == FULL && set[index] != key );
}
// if the index we found was removed: continue probing until we
// locate a free location or an element which equal()s the
// one we have.
if ( state == REMOVED) {
int firstRemoved = index;
while ( state != FREE && ( state == REMOVED || set[index] != key ) ) {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
}
if (state == FULL) {
return -index -1;
} else {
set[index] = key;
states[index] = FULL;
return firstRemoved;
}
}
// if it's full, the key is already stored
if (state == FULL) {
return -index -1;
} else {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index;
}
}
}
/** {@inheritDoc} */
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeInt( no_entry_key );
// NO_ENTRY_VALUE
out.writeLong( no_entry_value );
}
/** {@inheritDoc} */
public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readInt();
// NO_ENTRY_VALUE
no_entry_value = in.readLong();
}
} // TIntLongHash
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.*;
import gnu.trove.impl.HashFunctions;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed hashing implementation for long/long primitive entries.
*
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TLongLongHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of longs */
public transient long[] _set;
/**
* key that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected long no_entry_key;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected long no_entry_value;
protected boolean consumeFreeSlot;
/**
* Creates a new <code>T#E#Hash</code> instance with the default
* capacity and load factor.
*/
public TLongLongHash() {
super();
no_entry_key = ( long ) 0;
no_entry_value = ( long ) 0;
}
/**
* Creates a new <code>T#E#Hash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongLongHash( int initialCapacity ) {
super( initialCapacity );
no_entry_key = ( long ) 0;
no_entry_value = ( long ) 0;
}
/**
* Creates a new <code>TLongLongHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TLongLongHash( int initialCapacity, float loadFactor ) {
super(initialCapacity, loadFactor);
no_entry_key = ( long ) 0;
no_entry_value = ( long ) 0;
}
/**
* Creates a new <code>TLongLongHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TLongLongHash( int initialCapacity, float loadFactor,
long no_entry_key, long no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_key = no_entry_key;
this.no_entry_value = no_entry_value;
}
/**
* Returns the value that is used to represent null as a key. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryKey() {
return no_entry_key;
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryValue() {
return no_entry_value;
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_set = new long[capacity];
return capacity;
}
/**
* Searches the set for <tt>val</tt>
*
* @param val an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( long val ) {
return index(val) >= 0;
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
public boolean forEach( TLongProcedure procedure ) {
byte[] states = _states;
long[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( set[i] ) ) {
return false;
}
}
return true;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_set[index] = no_entry_key;
super.removeAt( index );
}
/**
* Locates the index of <tt>val</tt>.
*
* @param key an <code>long</code> value
* @return the index of <tt>val</tt> or -1 if it isn't in the set.
*/
protected int index( long key ) {
int hash, probe, index, length;
final byte[] states = _states;
final long[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == key)
return index;
return indexRehashed(key, index, hash, state);
}
int indexRehashed(long key, int index, int hash, byte state) {
// see Knuth, p. 529
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
//
if (state == FREE)
return -1;
//
if (key == _set[index])
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>val</tt> can be inserted. if
* there is already a value equal()ing <tt>val</tt> in the set,
* returns that value as a negative integer.
*
* @param key an <code>long</code> value
* @return an <code>int</code> value
*/
protected int insertKey( long val ) {
int hash, index;
hash = HashFunctions.hash(val) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index; // empty, all done
}
if (state == FULL && _set[index] == val) {
return -index - 1; // already stored
}
// already FULL or REMOVED, must probe
return insertKeyRehash(val, index, hash, state);
}
int insertKeyRehash(long val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, long val) {
_set[index] = val; // insert value
_states[index] = FULL;
}
protected int XinsertKey( long key ) {
int hash, probe, index, length;
final byte[] states = _states;
final long[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
consumeFreeSlot = false;
if ( state == FREE ) {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index; // empty, all done
} else if ( state == FULL && set[index] == key ) {
return -index -1; // already stored
} else { // already FULL or REMOVED, must probe
// compute the double hash
probe = 1 + ( hash % ( length - 2 ) );
// if the slot we landed on is FULL (but not removed), probe
// until we find an empty slot, a REMOVED slot, or an element
// equal to the one we are trying to insert.
// finding an empty slot means that the value is not present
// and that we should use that slot as the insertion point;
// finding a REMOVED slot means that we need to keep searching,
// however we want to remember the offset of that REMOVED slot
// so we can reuse it in case a "new" insertion (i.e. not an update)
// is possible.
// finding a matching value means that we've found that our desired
// key is already in the table
if ( state != REMOVED ) {
// starting at the natural offset, probe until we find an
// offset that isn't full.
do {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
} while ( state == FULL && set[index] != key );
}
// if the index we found was removed: continue probing until we
// locate a free location or an element which equal()s the
// one we have.
if ( state == REMOVED) {
int firstRemoved = index;
while ( state != FREE && ( state == REMOVED || set[index] != key ) ) {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
}
if (state == FULL) {
return -index -1;
} else {
set[index] = key;
states[index] = FULL;
return firstRemoved;
}
}
// if it's full, the key is already stored
if (state == FULL) {
return -index -1;
} else {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index;
}
}
}
/** {@inheritDoc} */
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeLong( no_entry_key );
// NO_ENTRY_VALUE
out.writeLong( no_entry_value );
}
/** {@inheritDoc} */
public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readLong();
// NO_ENTRY_VALUE
no_entry_value = in.readLong();
}
} // TLongLongHash
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.TObjectProcedure;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* An open addressed hashing implementation for Object types.
* <p/>
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: TObjectHash.java,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TObjectHash<T> extends THash {
@SuppressWarnings({"UnusedDeclaration"})
static final long serialVersionUID = -3461112548087185871L;
/**
* the set of Objects
*/
public transient Object[] _set;
public static final Object REMOVED = new Object(), FREE = new Object();
/**
* Indicates whether the last insertKey() call used a FREE slot. This field
* should be inspected right after call insertKey()
*/
protected boolean consumeFreeSlot;
/**
* Creates a new <code>TObjectHash</code> instance with the
* default capacity and load factor.
*/
public TObjectHash() {
super();
}
/**
* Creates a new <code>TObjectHash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TObjectHash(int initialCapacity) {
super(initialCapacity);
}
/**
* Creates a new <code>TObjectHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TObjectHash(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}
public int capacity() {
return _set.length;
}
protected void removeAt(int index) {
_set[index] = REMOVED;
super.removeAt(index);
}
/**
* initializes the Object set of this hash table.
*
* @param initialCapacity an <code>int</code> value
* @return an <code>int</code> value
*/
public int setUp(int initialCapacity) {
int capacity;
capacity = super.setUp(initialCapacity);
_set = new Object[capacity];
Arrays.fill(_set, FREE);
return capacity;
}
/**
* Executes <tt>procedure</tt> for each element in the set.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
@SuppressWarnings({"unchecked"})
public boolean forEach(TObjectProcedure<? super T> procedure) {
Object[] set = _set;
for (int i = set.length; i-- > 0;) {
if (set[i] != FREE
&& set[i] != REMOVED
&& !procedure.execute((T) set[i])) {
return false;
}
}
return true;
}
/**
* Searches the set for <tt>obj</tt>
*
* @param obj an <code>Object</code> value
* @return a <code>boolean</code> value
*/
@SuppressWarnings({"unchecked"})
public boolean contains(Object obj) {
return index(obj) >= 0;
}
/**
* Locates the index of <tt>obj</tt>.
*
* @param obj an <code>Object</code> value
* @return the index of <tt>obj</tt> or -1 if it isn't in the set.
*/
protected int index(Object obj) {
if (obj == null)
return indexForNull();
// From here on we know obj to be non-null
final int hash = hash(obj) & 0x7fffffff;
int index = hash % _set.length;
Object cur = _set[index];
if (cur == FREE) {
return -1;
}
if (cur == obj || equals(obj, cur)) {
return index;
}
return indexRehashed(obj, index, hash, cur);
}
/**
* Locates the index of non-null <tt>obj</tt>.
*
* @param obj target key, know to be non-null
* @param index we start from
* @param hash
* @param cur
* @return
*/
private int indexRehashed(Object obj, int index, int hash, Object cur) {
final Object[] set = _set;
final int length = set.length;
// NOTE: here it has to be REMOVED or FULL (some user-given value)
// see Knuth, p. 529
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
cur = set[index];
//
if (cur == FREE)
return -1;
//
if ((cur == obj || equals(obj, cur)))
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index <tt>null</tt>.
* <p/>
* null specific loop exploiting several properties to simplify the iteration logic
* - the null value hashes to 0 we so we can iterate from the beginning.
* - the probe value is 1 for this case
* - object identity can be used to match this case
* <p/>
* --> this result a simpler loop
*
* @return
*/
private int indexForNull() {
int index = 0;
for (Object o : _set) {
if (o == null)
return index;
if (o == FREE)
return -1;
index++;
}
return -1;
}
/**
* Alias introduced to avoid breaking the API. The new method name insertKey() reflects the
* changes made to the logic.
*
* @param obj
* @return
* @deprecated use {@link #insertKey} instead
*/
@Deprecated
protected int insertionIndex(T obj) {
return insertKey(obj);
}
/**
* Locates the index at which <tt>key</tt> can be inserted. if
* there is already a value equal()ing <tt>key</tt> in the set,
* returns that value's index as <tt>-index - 1</tt>.
* <p/>
* If a slot is found the value is inserted. When a FREE slot is used the consumeFreeSlot field is
* set to true. This field should be used in the method invoking insertKey() to pass to postInsertHook()
*
* @param key an <code>Object</code> value
* @return the index of a FREE slot at which key can be inserted
* or, if key is already stored in the hash, the negative value of
* that index, minus 1: -index -1.
*/
protected int insertKey(T key) {
consumeFreeSlot = false;
if (key == null)
return insertKeyForNull();
final int hash = hash(key) & 0x7fffffff;
int index = hash % _set.length;
Object cur = _set[index];
if (cur == FREE) {
consumeFreeSlot = true;
_set[index] = key; // insert value
return index; // empty, all done
}
if (cur == key || equals(key, cur)) {
return -index - 1; // already stored
}
return insertKeyRehash(key, index, hash, cur);
}
/**
* Looks for a slot using double hashing for a non-null key values and inserts the value
* in the slot
*
* @param key non-null key value
* @param index natural index
* @param hash
* @param cur value of first matched slot
* @return
*/
private int insertKeyRehash(T key, int index, int hash, Object cur) {
final Object[] set = _set;
final int length = set.length;
// already FULL or REMOVED, must probe
// compute the double hash
final int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (cur == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
cur = set[index];
// A FREE slot stops the search
if (cur == FREE) {
if (firstRemoved != -1) {
_set[firstRemoved] = key;
return firstRemoved;
} else {
consumeFreeSlot = true;
_set[index] = key; // insert value
return index;
}
}
if (cur == key || equals(key, cur)) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
_set[firstRemoved] = key;
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
/**
* Looks for a slot using double hashing for a null key value and inserts the value.
* <p/>
* null specific loop exploiting several properties to simplify the iteration logic
* - the null value hashes to 0 we so we can iterate from the beginning.
* - the probe value is 1 for this case
* - object identity can be used to match this case
*
* @return
*/
private int insertKeyForNull() {
int index = 0;
int firstRemoved = -1;
// Look for a slot containing the 'null' value as key
for (Object o : _set) {
// Locate first removed
if (o == REMOVED && firstRemoved == -1)
firstRemoved = index;
if (o == FREE) {
if (firstRemoved != -1) {
_set[firstRemoved] = null;
return firstRemoved;
} else {
consumeFreeSlot = true;
_set[index] = null; // insert value
return index;
}
}
if (o == null) {
return -index - 1;
}
index++;
}
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
_set[firstRemoved] = null;
return firstRemoved;
}
// We scanned the entire key set and found nothing, is set full?
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("Could not find insertion index for null key. Key set full!?!!");
}
/**
* Convenience methods for subclasses to use in throwing exceptions about
* badly behaved user objects employed as keys. We have to throw an
* IllegalArgumentException with a rather verbose message telling the
* user that they need to fix their object implementation to conform
* to the general contract for java.lang.Object.
*
*
* @param o1 the first of the equal elements with unequal hash codes.
* @param o2 the second of the equal elements with unequal hash codes.
* @throws IllegalArgumentException the whole point of this method.
*/
protected final void throwObjectContractViolation(Object o1, Object o2)
throws IllegalArgumentException {
throw buildObjectContractViolation(o1, o2, "");
}
/**
* Convenience methods for subclasses to use in throwing exceptions about
* badly behaved user objects employed as keys. We have to throw an
* IllegalArgumentException with a rather verbose message telling the
* user that they need to fix their object implementation to conform
* to the general contract for java.lang.Object.
*
*
* @param o1 the first of the equal elements with unequal hash codes.
* @param o2 the second of the equal elements with unequal hash codes.
* @param size
*@param oldSize
* @param oldKeys @throws IllegalArgumentException the whole point of this method.
*/
protected final void throwObjectContractViolation(Object o1, Object o2, int size, int oldSize, Object[] oldKeys)
throws IllegalArgumentException {
String extra = dumpExtraInfo(o1, o2, size(), oldSize, oldKeys);
throw buildObjectContractViolation(o1, o2, extra);
}
/**
* Convenience methods for subclasses to use in throwing exceptions about
* badly behaved user objects employed as keys. We have to throw an
* IllegalArgumentException with a rather verbose message telling the
* user that they need to fix their object implementation to conform
* to the general contract for java.lang.Object.
*
*
* @param o1 the first of the equal elements with unequal hash codes.
* @param o2 the second of the equal elements with unequal hash codes.
* @throws IllegalArgumentException the whole point of this method.
*/
protected final IllegalArgumentException buildObjectContractViolation(Object o1, Object o2, String extra ) {
return new IllegalArgumentException("Equal objects must have equal hashcodes. " +
"During rehashing, Trove discovered that the following two objects claim " +
"to be equal (as in java.lang.Object.equals()) but their hashCodes (or " +
"those calculated by your TObjectHashingStrategy) are not equal." +
"This violates the general contract of java.lang.Object.hashCode(). See " +
"bullet point two in that method's documentation. object #1 =" + objectInfo(o1) +
"; object #2 =" + objectInfo(o2) + "\n" + extra);
}
protected boolean equals(Object notnull, Object two) {
if (two == null || two == REMOVED)
return false;
return notnull.equals(two);
}
protected int hash(Object notnull) {
return notnull.hashCode();
}
protected static String reportPotentialConcurrentMod(int newSize, int oldSize) {
// Note that we would not be able to detect concurrent paired of put()-remove()
// operations with this simple check
if (newSize != oldSize)
return "[Warning] apparent concurrent modification of the key set. " +
"Size before and after rehash() do not match " + oldSize + " vs " + newSize;
return "";
}
/**
*
* @param newVal the key being inserted
* @param oldVal the key already stored at that position
* @param currentSize size of the key set during rehashing
* @param oldSize size of the key set before rehashing
* @param oldKeys the old key set
*/
protected String dumpExtraInfo(Object newVal, Object oldVal, int currentSize, int oldSize, Object[] oldKeys) {
StringBuilder b = new StringBuilder();
//
b.append(dumpKeyTypes(newVal, oldVal));
b.append(reportPotentialConcurrentMod(currentSize, oldSize));
b.append(detectKeyLoss(oldKeys, oldSize));
// Is de same object already present? Double insert?
if (newVal == oldVal) {
b.append("Inserting same object twice, rehashing bug. Object= ").append(oldVal);
}
return b.toString();
}
/**
* Detect inconsistent hashCode() and/or equals() methods
*
* @param keys
* @param oldSize
* @return
*/
private static String detectKeyLoss(Object[] keys, int oldSize) {
StringBuilder buf = new StringBuilder();
Set<Object> k = makeKeySet(keys);
if (k.size() != oldSize) {
buf.append("\nhashCode() and/or equals() have inconsistent implementation");
buf.append("\nKey set lost entries, now got ").append(k.size()).append(" instead of ").append(oldSize);
buf.append(". This can manifest itself as an apparent duplicate key.");
}
return buf.toString();
}
private static Set<Object> makeKeySet(Object[] keys) {
Set<Object> types = new HashSet<Object>();
for (Object o : keys) {
if (o != FREE && o != REMOVED) {
types.add(o);
}
}
return types;
}
private static String equalsSymmetryInfo(Object a, Object b) {
StringBuilder buf = new StringBuilder();
if (a == b) {
return "a == b";
}
if (a.getClass() != b.getClass()) {
buf.append("Class of objects differ a=").append(a.getClass()).append(" vs b=").append(b.getClass());
boolean aEb = a.equals(b);
boolean bEa = b.equals(a);
if (aEb != bEa) {
buf.append("\nequals() of a or b object are asymmetric");
buf.append("\na.equals(b) =").append(aEb);
buf.append("\nb.equals(a) =").append(bEa);
}
}
return buf.toString();
}
protected static String objectInfo(Object o) {
return (o == null ? "class null" : o.getClass()) + " id= " + System.identityHashCode(o)
+ " hashCode= " + (o == null ? 0 : o.hashCode()) + " toString= " + String.valueOf(o);
}
private String dumpKeyTypes(Object newVal, Object oldVal) {
StringBuilder buf = new StringBuilder();
Set<Class<?>> types = new HashSet<Class<?>>();
for (Object o : _set) {
if (o != FREE && o != REMOVED) {
if (o != null)
types.add(o.getClass());
else
types.add(null);
}
}
if (types.size() > 1) {
buf.append("\nMore than one type used for keys. Watch out for asymmetric equals(). " +
"Read about the 'Liskov substitution principle' and the implications for equals() in java.");
buf.append("\nKey types: ").append(types);
buf.append(equalsSymmetryInfo(newVal, oldVal));
}
return buf.toString();
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte(0);
// SUPER
super.writeExternal(out);
}
@Override
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal(in);
}
} // TObjectHash
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.Constants;
import java.util.Arrays;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed hashing implementation for long primitives.
*
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman, Rob Eden, Jeff Randall
* @version $Id: _E_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TLongHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of longs */
public transient long[] _set;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected long no_entry_value;
protected boolean consumeFreeSlot;
/**
* Creates a new <code>TLongHash</code> instance with the default
* capacity and load factor.
*/
public TLongHash() {
super();
no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TLongHash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongHash( int initialCapacity ) {
super( initialCapacity );
no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TLongHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TLongHash( int initialCapacity, float loadFactor ) {
super(initialCapacity, loadFactor);
no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TLongHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TLongHash( int initialCapacity, float loadFactor, long no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_value = no_entry_value;
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryValue() {
return no_entry_value;
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_set = new long[capacity];
return capacity;
}
/**
* Searches the set for <tt>val</tt>
*
* @param val an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( long val ) {
return index(val) >= 0;
}
/**
* Executes <tt>procedure</tt> for each element in the set.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
public boolean forEach( TLongProcedure procedure ) {
byte[] states = _states;
long[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( set[i] ) ) {
return false;
}
}
return true;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_set[index] = no_entry_value;
super.removeAt( index );
}
/**
* Locates the index of <tt>val</tt>.
*
* @param val an <code>long</code> value
* @return the index of <tt>val</tt> or -1 if it isn't in the set.
*/
protected int index( long val ) {
int hash, probe, index, length;
final byte[] states = _states;
final long[] set = _set;
length = states.length;
hash = HashFunctions.hash( val ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == val)
return index;
return indexRehashed(val, index, hash, state);
}
int indexRehashed(long key, int index, int hash, byte state) {
// see Knuth, p. 529
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
//
if (state == FREE)
return -1;
//
if (key == _set[index])
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>val</tt> can be inserted. if
* there is already a value equal()ing <tt>val</tt> in the set,
* returns that value as a negative integer.
*
* @param val an <code>long</code> value
* @return an <code>int</code> value
*/
protected int insertKey( long val ) {
int hash, index;
hash = HashFunctions.hash(val) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index; // empty, all done
}
if (state == FULL && _set[index] == val) {
return -index - 1; // already stored
}
// already FULL or REMOVED, must probe
return insertKeyRehash(val, index, hash, state);
}
int insertKeyRehash(long val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, long val) {
_set[index] = val; // insert value
_states[index] = FULL;
}
} // TLongHash
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.*;
import gnu.trove.impl.HashFunctions;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed hashing implementation for long/int primitive entries.
*
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TLongIntHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of longs */
public transient long[] _set;
/**
* key that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected long no_entry_key;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected int no_entry_value;
protected boolean consumeFreeSlot;
/**
* Creates a new <code>T#E#Hash</code> instance with the default
* capacity and load factor.
*/
public TLongIntHash() {
super();
no_entry_key = ( long ) 0;
no_entry_value = ( int ) 0;
}
/**
* Creates a new <code>T#E#Hash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongIntHash( int initialCapacity ) {
super( initialCapacity );
no_entry_key = ( long ) 0;
no_entry_value = ( int ) 0;
}
/**
* Creates a new <code>TLongIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TLongIntHash( int initialCapacity, float loadFactor ) {
super(initialCapacity, loadFactor);
no_entry_key = ( long ) 0;
no_entry_value = ( int ) 0;
}
/**
* Creates a new <code>TLongIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TLongIntHash( int initialCapacity, float loadFactor,
long no_entry_key, int no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_key = no_entry_key;
this.no_entry_value = no_entry_value;
}
/**
* Returns the value that is used to represent null as a key. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryKey() {
return no_entry_key;
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryValue() {
return no_entry_value;
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_set = new long[capacity];
return capacity;
}
/**
* Searches the set for <tt>val</tt>
*
* @param val an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( long val ) {
return index(val) >= 0;
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
public boolean forEach( TLongProcedure procedure ) {
byte[] states = _states;
long[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( set[i] ) ) {
return false;
}
}
return true;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_set[index] = no_entry_key;
super.removeAt( index );
}
/**
* Locates the index of <tt>val</tt>.
*
* @param key an <code>long</code> value
* @return the index of <tt>val</tt> or -1 if it isn't in the set.
*/
protected int index( long key ) {
int hash, probe, index, length;
final byte[] states = _states;
final long[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == key)
return index;
return indexRehashed(key, index, hash, state);
}
int indexRehashed(long key, int index, int hash, byte state) {
// see Knuth, p. 529
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
//
if (state == FREE)
return -1;
//
if (key == _set[index])
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>val</tt> can be inserted. if
* there is already a value equal()ing <tt>val</tt> in the set,
* returns that value as a negative integer.
*
* @param key an <code>long</code> value
* @return an <code>int</code> value
*/
protected int insertKey( long val ) {
int hash, index;
hash = HashFunctions.hash(val) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index; // empty, all done
}
if (state == FULL && _set[index] == val) {
return -index - 1; // already stored
}
// already FULL or REMOVED, must probe
return insertKeyRehash(val, index, hash, state);
}
int insertKeyRehash(long val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, long val) {
_set[index] = val; // insert value
_states[index] = FULL;
}
protected int XinsertKey( long key ) {
int hash, probe, index, length;
final byte[] states = _states;
final long[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
consumeFreeSlot = false;
if ( state == FREE ) {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index; // empty, all done
} else if ( state == FULL && set[index] == key ) {
return -index -1; // already stored
} else { // already FULL or REMOVED, must probe
// compute the double hash
probe = 1 + ( hash % ( length - 2 ) );
// if the slot we landed on is FULL (but not removed), probe
// until we find an empty slot, a REMOVED slot, or an element
// equal to the one we are trying to insert.
// finding an empty slot means that the value is not present
// and that we should use that slot as the insertion point;
// finding a REMOVED slot means that we need to keep searching,
// however we want to remember the offset of that REMOVED slot
// so we can reuse it in case a "new" insertion (i.e. not an update)
// is possible.
// finding a matching value means that we've found that our desired
// key is already in the table
if ( state != REMOVED ) {
// starting at the natural offset, probe until we find an
// offset that isn't full.
do {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
} while ( state == FULL && set[index] != key );
}
// if the index we found was removed: continue probing until we
// locate a free location or an element which equal()s the
// one we have.
if ( state == REMOVED) {
int firstRemoved = index;
while ( state != FREE && ( state == REMOVED || set[index] != key ) ) {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
}
if (state == FULL) {
return -index -1;
} else {
set[index] = key;
states[index] = FULL;
return firstRemoved;
}
}
// if it's full, the key is already stored
if (state == FULL) {
return -index -1;
} else {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index;
}
}
}
/** {@inheritDoc} */
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeLong( no_entry_key );
// NO_ENTRY_VALUE
out.writeInt( no_entry_value );
}
/** {@inheritDoc} */
public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readLong();
// NO_ENTRY_VALUE
no_entry_value = in.readInt();
}
} // TLongIntHash
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.iterator.TIntIterator;
import gnu.trove.procedure.TIntProcedure;
import java.util.Collection;
import java.io.Serializable;
/**
* An interface that mimics the <tt>Collection</tt> interface.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _E_Collection.template,v 1.1.2.2 2009/09/15 02:38:30 upholderoftruth Exp $
*/
public interface TIntCollection {
static final long serialVersionUID = 1L;
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
int getNoEntryValue();
/**
* Returns the number of elements in this collection (its cardinality). If this
* collection contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this collection (its cardinality)
*/
int size();
/**
* Returns <tt>true</tt> if this collection contains no elements.
*
* @return <tt>true</tt> if this collection contains no elements
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this collection contains the specified element.
*
* @param entry an <code>int</code> value
* @return true if the collection contains the specified element.
*/
boolean contains( int entry );
/**
* Creates an iterator over the values of the collection. The iterator
* supports element deletion.
*
* @return an <code>TIntIterator</code> value
*/
TIntIterator iterator();
/**
* Returns an array containing all of the elements in this collection.
* If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the
* elements in the same order.
*
* <p>The returned array will be "safe" in that no references to it
* are maintained by this collection. (In other words, this method must
* allocate a new array even if this collection is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all the elements in this collection
*/
int[] toArray();
/**
* Returns an array containing elements in this collection.
*
* <p>If this collection fits in the specified array with room to spare
* (i.e., the array has more elements than this collection), the element in
* the array immediately following the end of the collection is collection to
* <tt>{@link #getNoEntryValue()}</tt>. (This is useful in determining
* the length of this collection <i>only</i> if the caller knows that this
* collection does not contain any elements representing null.)
*
* <p>If the native array is smaller than the collection size,
* the array will be filled with elements in Iterator order
* until it is full and exclude the remainder.
*
* <p>If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements
* in the same order.
*
* @param dest the array into which the elements of this collection are to be
* stored.
* @return an <tt>int[]</tt> containing all the elements in this collection
* @throws NullPointerException if the specified array is null
*/
int[] toArray( int[] dest );
/**
* Inserts a value into the collection.
*
* @param entry a <code>int</code> value
* @return true if the collection was modified by the add operation
*/
boolean add( int entry );
/**
* Removes <tt>entry</tt> from the collection.
*
* @param entry an <code>int</code> value
* @return true if the collection was modified by the remove operation.
*/
boolean remove( int entry );
/**
* Tests the collection to determine if all of the elements in
* <tt>collection</tt> are present.
*
* @param collection a <code>Collection</code> value
* @return true if all elements were present in the collection.
*/
boolean containsAll( Collection<?> collection );
/**
* Tests the collection to determine if all of the elements in
* <tt>TIntCollection</tt> are present.
*
* @param collection a <code>TIntCollection</code> value
* @return true if all elements were present in the collection.
*/
boolean containsAll( TIntCollection collection );
/**
* Tests the collection to determine if all of the elements in
* <tt>array</tt> are present.
*
* @param array as <code>array</code> of int primitives.
* @return true if all elements were present in the collection.
*/
boolean containsAll( int[] array );
/**
* Adds all of the elements in <tt>collection</tt> to the collection.
*
* @param collection a <code>Collection</code> value
* @return true if the collection was modified by the add all operation.
*/
boolean addAll( Collection<? extends Integer> collection );
/**
* Adds all of the elements in the <tt>TIntCollection</tt> to the collection.
*
* @param collection a <code>TIntCollection</code> value
* @return true if the collection was modified by the add all operation.
*/
boolean addAll( TIntCollection collection );
/**
* Adds all of the elements in the <tt>array</tt> to the collection.
*
* @param array a <code>array</code> of int primitives.
* @return true if the collection was modified by the add all operation.
*/
boolean addAll( int[] array );
/**
* Removes any values in the collection which are not contained in
* <tt>collection</tt>.
*
* @param collection a <code>Collection</code> value
* @return true if the collection was modified by the retain all operation
*/
boolean retainAll( Collection<?> collection );
/**
* Removes any values in the collection which are not contained in
* <tt>TIntCollection</tt>.
*
* @param collection a <code>TIntCollection</code> value
* @return true if the collection was modified by the retain all operation
*/
boolean retainAll( TIntCollection collection );
/**
* Removes any values in the collection which are not contained in
* <tt>array</tt>.
*
* @param array an <code>array</code> of int primitives.
* @return true if the collection was modified by the retain all operation
*/
boolean retainAll( int[] array );
/**
* Removes all of the elements in <tt>collection</tt> from the collection.
*
* @param collection a <code>Collection</code> value
* @return true if the collection was modified by the remove all operation.
*/
boolean removeAll( Collection<?> collection );
/**
* Removes all of the elements in <tt>TIntCollection</tt> from the collection.
*
* @param collection a <code>TIntCollection</code> value
* @return true if the collection was modified by the remove all operation.
*/
boolean removeAll( TIntCollection collection );
/**
* Removes all of the elements in <tt>array</tt> from the collection.
*
* @param array an <code>array</code> of int primitives.
* @return true if the collection was modified by the remove all operation.
*/
boolean removeAll( int[] array );
/**
* Empties the collection.
*/
void clear();
/**
* Executes <tt>procedure</tt> for each element in the collection.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the collection terminated because
* the procedure returned false for some value.
*/
boolean forEach( TIntProcedure procedure );
// Comparison and hashing
/**
* Compares the specified object with this collection for equality. Returns
* <tt>true</tt> if the specified object is also a collection, the two collection
* have the same size, and every member of the specified collection is
* contained in this collection (or equivalently, every member of this collection is
* contained in the specified collection). This definition ensures that the
* equals method works properly across different implementations of the
* collection interface.
*
* @param o object to be compared for equality with this collection
* @return <tt>true</tt> if the specified object is equal to this collection
*/
boolean equals( Object o );
/**
* Returns the hash code value for this collection. The hash code of a collection is
* defined to be the sum of the hash codes of the elements in the collection.
* This ensures that <tt>s1.equals(s2)</tt> implies that
* <tt>s1.hashCode()==s2.hashCode()</tt> for any two collection <tt>s1</tt>
* and <tt>s2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this collection
* @see Object#equals(Object)
* @see Collection#equals(Object)
*/
int hashCode();
} // TIntCollection
| Java |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.iterator.TLongIterator;
import gnu.trove.procedure.TLongProcedure;
import java.util.Collection;
import java.io.Serializable;
/**
* An interface that mimics the <tt>Collection</tt> interface.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _E_Collection.template,v 1.1.2.2 2009/09/15 02:38:30 upholderoftruth Exp $
*/
public interface TLongCollection {
static final long serialVersionUID = 1L;
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
long getNoEntryValue();
/**
* Returns the number of elements in this collection (its cardinality). If this
* collection contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this collection (its cardinality)
*/
int size();
/**
* Returns <tt>true</tt> if this collection contains no elements.
*
* @return <tt>true</tt> if this collection contains no elements
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this collection contains the specified element.
*
* @param entry an <code>long</code> value
* @return true if the collection contains the specified element.
*/
boolean contains( long entry );
/**
* Creates an iterator over the values of the collection. The iterator
* supports element deletion.
*
* @return an <code>TLongIterator</code> value
*/
TLongIterator iterator();
/**
* Returns an array containing all of the elements in this collection.
* If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the
* elements in the same order.
*
* <p>The returned array will be "safe" in that no references to it
* are maintained by this collection. (In other words, this method must
* allocate a new array even if this collection is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all the elements in this collection
*/
long[] toArray();
/**
* Returns an array containing elements in this collection.
*
* <p>If this collection fits in the specified array with room to spare
* (i.e., the array has more elements than this collection), the element in
* the array immediately following the end of the collection is collection to
* <tt>{@link #getNoEntryValue()}</tt>. (This is useful in determining
* the length of this collection <i>only</i> if the caller knows that this
* collection does not contain any elements representing null.)
*
* <p>If the native array is smaller than the collection size,
* the array will be filled with elements in Iterator order
* until it is full and exclude the remainder.
*
* <p>If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements
* in the same order.
*
* @param dest the array into which the elements of this collection are to be
* stored.
* @return an <tt>long[]</tt> containing all the elements in this collection
* @throws NullPointerException if the specified array is null
*/
long[] toArray( long[] dest );
/**
* Inserts a value into the collection.
*
* @param entry a <code>long</code> value
* @return true if the collection was modified by the add operation
*/
boolean add( long entry );
/**
* Removes <tt>entry</tt> from the collection.
*
* @param entry an <code>long</code> value
* @return true if the collection was modified by the remove operation.
*/
boolean remove( long entry );
/**
* Tests the collection to determine if all of the elements in
* <tt>collection</tt> are present.
*
* @param collection a <code>Collection</code> value
* @return true if all elements were present in the collection.
*/
boolean containsAll( Collection<?> collection );
/**
* Tests the collection to determine if all of the elements in
* <tt>TLongCollection</tt> are present.
*
* @param collection a <code>TLongCollection</code> value
* @return true if all elements were present in the collection.
*/
boolean containsAll( TLongCollection collection );
/**
* Tests the collection to determine if all of the elements in
* <tt>array</tt> are present.
*
* @param array as <code>array</code> of long primitives.
* @return true if all elements were present in the collection.
*/
boolean containsAll( long[] array );
/**
* Adds all of the elements in <tt>collection</tt> to the collection.
*
* @param collection a <code>Collection</code> value
* @return true if the collection was modified by the add all operation.
*/
boolean addAll( Collection<? extends Long> collection );
/**
* Adds all of the elements in the <tt>TLongCollection</tt> to the collection.
*
* @param collection a <code>TLongCollection</code> value
* @return true if the collection was modified by the add all operation.
*/
boolean addAll( TLongCollection collection );
/**
* Adds all of the elements in the <tt>array</tt> to the collection.
*
* @param array a <code>array</code> of long primitives.
* @return true if the collection was modified by the add all operation.
*/
boolean addAll( long[] array );
/**
* Removes any values in the collection which are not contained in
* <tt>collection</tt>.
*
* @param collection a <code>Collection</code> value
* @return true if the collection was modified by the retain all operation
*/
boolean retainAll( Collection<?> collection );
/**
* Removes any values in the collection which are not contained in
* <tt>TLongCollection</tt>.
*
* @param collection a <code>TLongCollection</code> value
* @return true if the collection was modified by the retain all operation
*/
boolean retainAll( TLongCollection collection );
/**
* Removes any values in the collection which are not contained in
* <tt>array</tt>.
*
* @param array an <code>array</code> of long primitives.
* @return true if the collection was modified by the retain all operation
*/
boolean retainAll( long[] array );
/**
* Removes all of the elements in <tt>collection</tt> from the collection.
*
* @param collection a <code>Collection</code> value
* @return true if the collection was modified by the remove all operation.
*/
boolean removeAll( Collection<?> collection );
/**
* Removes all of the elements in <tt>TLongCollection</tt> from the collection.
*
* @param collection a <code>TLongCollection</code> value
* @return true if the collection was modified by the remove all operation.
*/
boolean removeAll( TLongCollection collection );
/**
* Removes all of the elements in <tt>array</tt> from the collection.
*
* @param array an <code>array</code> of long primitives.
* @return true if the collection was modified by the remove all operation.
*/
boolean removeAll( long[] array );
/**
* Empties the collection.
*/
void clear();
/**
* Executes <tt>procedure</tt> for each element in the collection.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the collection terminated because
* the procedure returned false for some value.
*/
boolean forEach( TLongProcedure procedure );
// Comparison and hashing
/**
* Compares the specified object with this collection for equality. Returns
* <tt>true</tt> if the specified object is also a collection, the two collection
* have the same size, and every member of the specified collection is
* contained in this collection (or equivalently, every member of this collection is
* contained in the specified collection). This definition ensures that the
* equals method works properly across different implementations of the
* collection interface.
*
* @param o object to be compared for equality with this collection
* @return <tt>true</tt> if the specified object is equal to this collection
*/
boolean equals( Object o );
/**
* Returns the hash code value for this collection. The hash code of a collection is
* defined to be the sum of the hash codes of the elements in the collection.
* This ensures that <tt>s1.equals(s2)</tt> implies that
* <tt>s1.hashCode()==s2.hashCode()</tt> for any two collection <tt>s1</tt>
* and <tt>s2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this collection
* @see Object#equals(Object)
* @see Collection#equals(Object)
*/
int hashCode();
} // TLongCollection
| Java |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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.
*/
package net.robotmedia.billing;
import java.util.LinkedList;
import static net.robotmedia.billing.BillingRequest.*;
import net.robotmedia.billing.utils.Compatibility;
import com.android.vending.billing.IMarketBillingService;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class BillingService extends Service implements ServiceConnection {
private static enum Action {
CHECK_BILLING_SUPPORTED, CONFIRM_NOTIFICATIONS, GET_PURCHASE_INFORMATION, REQUEST_PURCHASE, RESTORE_TRANSACTIONS,
}
private static final String ACTION_MARKET_BILLING_SERVICE = "com.android.vending.billing.MarketBillingService.BIND";
private static final String EXTRA_DEVELOPER_PAYLOAD = "DEVELOPER_PAYLOAD";
private static final String EXTRA_ITEM_ID = "ITEM_ID";
private static final String EXTRA_NONCE = "EXTRA_NONCE";
private static final String EXTRA_NOTIFY_IDS = "NOTIFY_IDS";
private static LinkedList<BillingRequest> mPendingRequests = new LinkedList<BillingRequest>();
private static IMarketBillingService mService;
public static void checkBillingSupported(Context context) {
final Intent intent = createIntent(context, Action.CHECK_BILLING_SUPPORTED);
context.startService(intent);
}
public static void confirmNotifications(Context context, String[] notifyIds) {
final Intent intent = createIntent(context, Action.CONFIRM_NOTIFICATIONS);
intent.putExtra(EXTRA_NOTIFY_IDS, notifyIds);
context.startService(intent);
}
private static Intent createIntent(Context context, Action action) {
final String actionString = getActionForIntent(context, action);
final Intent intent = new Intent(actionString);
intent.setClass(context, BillingService.class);
return intent;
}
private static final String getActionForIntent(Context context, Action action) {
return context.getPackageName() + "." + action.toString();
}
public static void getPurchaseInformation(Context context, String[] notifyIds, long nonce) {
final Intent intent = createIntent(context, Action.GET_PURCHASE_INFORMATION);
intent.putExtra(EXTRA_NOTIFY_IDS, notifyIds);
intent.putExtra(EXTRA_NONCE, nonce);
context.startService(intent);
}
public static void requestPurchase(Context context, String itemId, String developerPayload) {
final Intent intent = createIntent(context, Action.REQUEST_PURCHASE);
intent.putExtra(EXTRA_ITEM_ID, itemId);
intent.putExtra(EXTRA_DEVELOPER_PAYLOAD, developerPayload);
context.startService(intent);
}
public static void restoreTransations(Context context, long nonce) {
final Intent intent = createIntent(context, Action.RESTORE_TRANSACTIONS);
intent.setClass(context, BillingService.class);
intent.putExtra(EXTRA_NONCE, nonce);
context.startService(intent);
}
private void bindMarketBillingService() {
try {
final boolean bindResult = bindService(new Intent(ACTION_MARKET_BILLING_SERVICE), this, Context.BIND_AUTO_CREATE);
if (!bindResult) {
Log.e(this.getClass().getSimpleName(), "Could not bind to MarketBillingService");
}
} catch (SecurityException e) {
Log.e(this.getClass().getSimpleName(), "Could not bind to MarketBillingService", e);
}
}
private void checkBillingSupported(int startId) {
final String packageName = getPackageName();
final CheckBillingSupported request = new CheckBillingSupported(packageName, startId);
runRequestOrQueue(request);
}
private void confirmNotifications(Intent intent, int startId) {
final String packageName = getPackageName();
final String[] notifyIds = intent.getStringArrayExtra(EXTRA_NOTIFY_IDS);
final ConfirmNotifications request = new ConfirmNotifications(packageName, startId, notifyIds);
runRequestOrQueue(request);
}
private Action getActionFromIntent(Intent intent) {
final String actionString = intent.getAction();
if (actionString == null) {
return null;
}
final String[] split = actionString.split("\\.");
if (split.length <= 0) {
return null;
}
return Action.valueOf(split[split.length - 1]);
}
private void getPurchaseInformation(Intent intent, int startId) {
final String packageName = getPackageName();
final long nonce = intent.getLongExtra(EXTRA_NONCE, 0);
final String[] notifyIds = intent.getStringArrayExtra(EXTRA_NOTIFY_IDS);
final GetPurchaseInformation request = new GetPurchaseInformation(packageName, startId, notifyIds);
request.setNonce(nonce);
runRequestOrQueue(request);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IMarketBillingService.Stub.asInterface(service);
runPendingRequests();
}
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
handleCommand(intent, startId);
}
// @Override // Avoid compile errors on pre-2.0
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent, startId);
return Compatibility.START_NOT_STICKY;
}
private void handleCommand(Intent intent, int startId) {
final Action action = getActionFromIntent(intent);
if (action == null) {
return;
}
switch (action) {
case CHECK_BILLING_SUPPORTED:
checkBillingSupported(startId);
break;
case REQUEST_PURCHASE:
requestPurchase(intent, startId);
break;
case GET_PURCHASE_INFORMATION:
getPurchaseInformation(intent, startId);
break;
case CONFIRM_NOTIFICATIONS:
confirmNotifications(intent, startId);
break;
case RESTORE_TRANSACTIONS:
restoreTransactions(intent, startId);
}
}
private void requestPurchase(Intent intent, int startId) {
final String packageName = getPackageName();
final String itemId = intent.getStringExtra(EXTRA_ITEM_ID);
final String developerPayload = intent.getStringExtra(EXTRA_DEVELOPER_PAYLOAD);
final RequestPurchase request = new RequestPurchase(packageName, startId, itemId, developerPayload);
runRequestOrQueue(request);
}
private void restoreTransactions(Intent intent, int startId) {
final String packageName = getPackageName();
final long nonce = intent.getLongExtra(EXTRA_NONCE, 0);
final RestoreTransactions request = new RestoreTransactions(packageName, startId);
request.setNonce(nonce);
runRequestOrQueue(request);
}
private void runPendingRequests() {
BillingRequest request;
int maxStartId = -1;
while ((request = mPendingRequests.peek()) != null) {
if (mService != null) {
runRequest(request);
mPendingRequests.remove();
if (maxStartId < request.getStartId()) {
maxStartId = request.getStartId();
}
} else {
bindMarketBillingService();
return;
}
}
if (maxStartId >= 0) {
stopSelf(maxStartId);
}
}
private void runRequest(BillingRequest request) {
try {
final long requestId = request.run(mService);
BillingController.onRequestSent(requestId, request);
} catch (RemoteException e) {
Log.w(this.getClass().getSimpleName(), "Remote billing service crashed");
// TODO: Retry?
}
}
private void runRequestOrQueue(BillingRequest request) {
mPendingRequests.add(request);
if (mService == null) {
bindMarketBillingService();
} else {
runPendingRequests();
}
}
@Override
public void onDestroy() {
super.onDestroy();
// Ensure we're not leaking Android Market billing service
if (mService != null) {
try {
unbindService(this);
} catch (IllegalArgumentException e) {
// This might happen if the service was disconnected
}
}
}
}
| Java |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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.
*/
package net.robotmedia.billing;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class BillingReceiver extends BroadcastReceiver {
static final String ACTION_NOTIFY = "com.android.vending.billing.IN_APP_NOTIFY";
static final String ACTION_RESPONSE_CODE =
"com.android.vending.billing.RESPONSE_CODE";
static final String ACTION_PURCHASE_STATE_CHANGED =
"com.android.vending.billing.PURCHASE_STATE_CHANGED";
static final String EXTRA_NOTIFICATION_ID = "notification_id";
static final String EXTRA_INAPP_SIGNED_DATA = "inapp_signed_data";
static final String EXTRA_INAPP_SIGNATURE = "inapp_signature";
static final String EXTRA_REQUEST_ID = "request_id";
static final String EXTRA_RESPONSE_CODE = "response_code";
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
BillingController.debug("Received " + action);
if (ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
purchaseStateChanged(context, intent);
} else if (ACTION_NOTIFY.equals(action)) {
notify(context, intent);
} else if (ACTION_RESPONSE_CODE.equals(action)) {
responseCode(context, intent);
} else {
Log.w(this.getClass().getSimpleName(), "Unexpected action: " + action);
}
}
private void purchaseStateChanged(Context context, Intent intent) {
final String signedData = intent.getStringExtra(EXTRA_INAPP_SIGNED_DATA);
final String signature = intent.getStringExtra(EXTRA_INAPP_SIGNATURE);
BillingController.onPurchaseStateChanged(context, signedData, signature);
}
private void notify(Context context, Intent intent) {
String notifyId = intent.getStringExtra(EXTRA_NOTIFICATION_ID);
BillingController.onNotify(context, notifyId);
}
private void responseCode(Context context, Intent intent) {
final long requestId = intent.getLongExtra(EXTRA_REQUEST_ID, -1);
final int responseCode = intent.getIntExtra(EXTRA_RESPONSE_CODE, 0);
BillingController.onResponseCode(context, requestId, responseCode);
}
}
| Java |
// Copyright 2002, Google, 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.
package net.robotmedia.billing.utils;
/**
* Exception thrown when encountering an invalid Base64 input character.
*
* @author nelson
*/
public class Base64DecoderException extends Exception {
public Base64DecoderException() {
super();
}
public Base64DecoderException(String s) {
super(s);
}
private static final long serialVersionUID = 1L;
}
| Java |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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.
*/
package net.robotmedia.billing.utils;
import java.security.SecureRandom;
import java.util.HashSet;
import net.robotmedia.billing.utils.AESObfuscator.ValidationException;
import android.content.Context;
import android.provider.Settings;
import android.util.Log;
public class Security {
private static HashSet<Long> knownNonces = new HashSet<Long>();
private static final SecureRandom RANDOM = new SecureRandom();
private static final String TAG = Security.class.getSimpleName();
/** Generates a nonce (a random number used once). */
public static long generateNonce() {
long nonce = RANDOM.nextLong();
knownNonces.add(nonce);
return nonce;
}
public static boolean isNonceKnown(long nonce) {
return knownNonces.contains(nonce);
}
public static void removeNonce(long nonce) {
knownNonces.remove(nonce);
}
public static String obfuscate(Context context, byte[] salt, String original) {
final AESObfuscator obfuscator = getObfuscator(context, salt);
return obfuscator.obfuscate(original);
}
private static AESObfuscator _obfuscator = null;
private static AESObfuscator getObfuscator(Context context, byte[] salt) {
if (_obfuscator == null) {
final String installationId = Installation.id(context);
final String deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
final String password = installationId + deviceId + context.getPackageName();
_obfuscator = new AESObfuscator(salt, password);
}
return _obfuscator;
}
public static String unobfuscate(Context context, byte[] salt, String obfuscated) {
final AESObfuscator obfuscator = getObfuscator(context, salt);
try {
return obfuscator.unobfuscate(obfuscated);
} catch (ValidationException e) {
Log.w(TAG, "Invalid obfuscated data or key");
}
return null;
}
}
| Java |
// Portions copyright 2002, Google, 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.
package net.robotmedia.billing.utils;
// This code was converted from code at http://iharder.sourceforge.net/base64/
// Lots of extraneous features were removed.
/* The original code said:
* <p>
* I am placing this code in the Public Domain. Do with it as you will.
* This software comes with no guarantees or warranties but with
* plenty of well-wishing instead!
* Please visit
* <a href="http://iharder.net/xmlizable">http://iharder.net/xmlizable</a>
* periodically to check for updates or to contribute improvements.
* </p>
*
* @author Robert Harder
* @author rharder@usa.net
* @version 1.3
*/
/**
* Base64 converter class. This code is not a complete MIME encoder;
* it simply converts binary data to base64 data and back.
*
* <p>Note {@link CharBase64} is a GWT-compatible implementation of this
* class.
*/
public class Base64 {
/** Specify encoding (value is {@code true}). */
public final static boolean ENCODE = true;
/** Specify decoding (value is {@code false}). */
public final static boolean DECODE = false;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte) '=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte) '\n';
/**
* The 64 valid Base64 values.
*/
private final static byte[] ALPHABET =
{(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
(byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K',
(byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P',
(byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
(byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
(byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e',
(byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
(byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o',
(byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't',
(byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y',
(byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
(byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8',
(byte) '9', (byte) '+', (byte) '/'};
/**
* The 64 valid web safe Base64 values.
*/
private final static byte[] WEBSAFE_ALPHABET =
{(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
(byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K',
(byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P',
(byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
(byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
(byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e',
(byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
(byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o',
(byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't',
(byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y',
(byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
(byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8',
(byte) '9', (byte) '-', (byte) '_'};
/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
private final static byte[] DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
-5, -5, // Whitespace: Tab and Linefeed
-9, -9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
-9, -9, -9, -9, -9, // Decimal 27 - 31
-5, // Whitespace: Space
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9, -9, -9, // Decimal 44 - 46
63, // Slash at decimal 47
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
-9, -9, -9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9, -9, -9, // Decimal 62 - 64
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
-9, -9, -9, -9, -9, -9, // Decimal 91 - 96
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
-9, -9, -9, -9, -9 // Decimal 123 - 127
/* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/** The web safe decodabet */
private final static byte[] WEBSAFE_DECODABET =
{-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
-5, -5, // Whitespace: Tab and Linefeed
-9, -9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
-9, -9, -9, -9, -9, // Decimal 27 - 31
-5, // Whitespace: Space
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 44
62, // Dash '-' sign at decimal 45
-9, -9, // Decimal 46-47
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
-9, -9, -9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9, -9, -9, // Decimal 62 - 64
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
-9, -9, -9, -9, // Decimal 91-94
63, // Underscore '_' at decimal 95
-9, // Decimal 96
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
-9, -9, -9, -9, -9 // Decimal 123 - 127
/* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
// Indicates white space in encoding
private final static byte WHITE_SPACE_ENC = -5;
// Indicates equals sign in encoding
private final static byte EQUALS_SIGN_ENC = -1;
/** Defeats instantiation. */
private Base64() {
}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accommodate <var>srcOffset</var> + 3 for
* the <var>source</var> array or <var>destOffset</var> + 4 for
* the <var>destination</var> array.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @param alphabet is the encoding alphabet
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(byte[] source, int srcOffset,
int numSigBytes, byte[] destination, int destOffset, byte[] alphabet) {
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index alphabet
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff =
(numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
| (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
| (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
switch (numSigBytes) {
case 3:
destination[destOffset] = alphabet[(inBuff >>> 18)];
destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = alphabet[(inBuff) & 0x3f];
return destination;
case 2:
destination[destOffset] = alphabet[(inBuff >>> 18)];
destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
case 1:
destination[destOffset] = alphabet[(inBuff >>> 18)];
destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = EQUALS_SIGN;
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Encodes a byte array into Base64 notation.
* Equivalent to calling
* {@code encodeBytes(source, 0, source.length)}
*
* @param source The data to convert
* @since 1.4
*/
public static String encode(byte[] source) {
return encode(source, 0, source.length, ALPHABET, true);
}
/**
* Encodes a byte array into web safe Base64 notation.
*
* @param source The data to convert
* @param doPadding is {@code true} to pad result with '=' chars
* if it does not fall on 3 byte boundaries
*/
public static String encodeWebSafe(byte[] source, boolean doPadding) {
return encode(source, 0, source.length, WEBSAFE_ALPHABET, doPadding);
}
/**
* Encodes a byte array into Base64 notation.
*
* @param source the data to convert
* @param off offset in array where conversion should begin
* @param len length of data to convert
* @param alphabet the encoding alphabet
* @param doPadding is {@code true} to pad result with '=' chars
* if it does not fall on 3 byte boundaries
* @since 1.4
*/
public static String encode(byte[] source, int off, int len, byte[] alphabet,
boolean doPadding) {
byte[] outBuff = encode(source, off, len, alphabet, Integer.MAX_VALUE);
int outLen = outBuff.length;
// If doPadding is false, set length to truncate '='
// padding characters
while (doPadding == false && outLen > 0) {
if (outBuff[outLen - 1] != '=') {
break;
}
outLen -= 1;
}
return new String(outBuff, 0, outLen);
}
/**
* Encodes a byte array into Base64 notation.
*
* @param source the data to convert
* @param off offset in array where conversion should begin
* @param len length of data to convert
* @param alphabet is the encoding alphabet
* @param maxLineLength maximum length of one line.
* @return the BASE64-encoded byte array
*/
public static byte[] encode(byte[] source, int off, int len, byte[] alphabet,
int maxLineLength) {
int lenDiv3 = (len + 2) / 3; // ceil(len / 3)
int len43 = lenDiv3 * 4;
byte[] outBuff = new byte[len43 // Main 4:3
+ (len43 / maxLineLength)]; // New lines
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for (; d < len2; d += 3, e += 4) {
// The following block of code is the same as
// encode3to4( source, d + off, 3, outBuff, e, alphabet );
// but inlined for faster encoding (~20% improvement)
int inBuff =
((source[d + off] << 24) >>> 8)
| ((source[d + 1 + off] << 24) >>> 16)
| ((source[d + 2 + off] << 24) >>> 24);
outBuff[e] = alphabet[(inBuff >>> 18)];
outBuff[e + 1] = alphabet[(inBuff >>> 12) & 0x3f];
outBuff[e + 2] = alphabet[(inBuff >>> 6) & 0x3f];
outBuff[e + 3] = alphabet[(inBuff) & 0x3f];
lineLength += 4;
if (lineLength == maxLineLength) {
outBuff[e + 4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // end for: each piece of array
if (d < len) {
encode3to4(source, d + off, len - d, outBuff, e, alphabet);
lineLength += 4;
if (lineLength == maxLineLength) {
// Add a last newline
outBuff[e + 4] = NEW_LINE;
e++;
}
e += 4;
}
assert (e == outBuff.length);
return outBuff;
}
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accommodate <var>srcOffset</var> + 4 for
* the <var>source</var> array or <var>destOffset</var> + 3 for
* the <var>destination</var> array.
* This method returns the actual number of bytes that
* were converted from the Base64 encoding.
*
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @param decodabet the decodabet for decoding Base64 content
* @return the number of decoded bytes converted
* @since 1.3
*/
private static int decode4to3(byte[] source, int srcOffset,
byte[] destination, int destOffset, byte[] decodabet) {
// Example: Dk==
if (source[srcOffset + 2] == EQUALS_SIGN) {
int outBuff =
((decodabet[source[srcOffset]] << 24) >>> 6)
| ((decodabet[source[srcOffset + 1]] << 24) >>> 12);
destination[destOffset] = (byte) (outBuff >>> 16);
return 1;
} else if (source[srcOffset + 3] == EQUALS_SIGN) {
// Example: DkL=
int outBuff =
((decodabet[source[srcOffset]] << 24) >>> 6)
| ((decodabet[source[srcOffset + 1]] << 24) >>> 12)
| ((decodabet[source[srcOffset + 2]] << 24) >>> 18);
destination[destOffset] = (byte) (outBuff >>> 16);
destination[destOffset + 1] = (byte) (outBuff >>> 8);
return 2;
} else {
// Example: DkLE
int outBuff =
((decodabet[source[srcOffset]] << 24) >>> 6)
| ((decodabet[source[srcOffset + 1]] << 24) >>> 12)
| ((decodabet[source[srcOffset + 2]] << 24) >>> 18)
| ((decodabet[source[srcOffset + 3]] << 24) >>> 24);
destination[destOffset] = (byte) (outBuff >> 16);
destination[destOffset + 1] = (byte) (outBuff >> 8);
destination[destOffset + 2] = (byte) (outBuff);
return 3;
}
} // end decodeToBytes
/**
* Decodes data from Base64 notation.
*
* @param s the string to decode (decoded in default encoding)
* @return the decoded data
* @since 1.4
*/
public static byte[] decode(String s) throws Base64DecoderException {
byte[] bytes = s.getBytes();
return decode(bytes, 0, bytes.length);
}
/**
* Decodes data from web safe Base64 notation.
* Web safe encoding uses '-' instead of '+', '_' instead of '/'
*
* @param s the string to decode (decoded in default encoding)
* @return the decoded data
*/
public static byte[] decodeWebSafe(String s) throws Base64DecoderException {
byte[] bytes = s.getBytes();
return decodeWebSafe(bytes, 0, bytes.length);
}
/**
* Decodes Base64 content in byte array format and returns
* the decoded byte array.
*
* @param source The Base64 encoded data
* @return decoded data
* @since 1.3
* @throws Base64DecoderException
*/
public static byte[] decode(byte[] source) throws Base64DecoderException {
return decode(source, 0, source.length);
}
/**
* Decodes web safe Base64 content in byte array format and returns
* the decoded data.
* Web safe encoding uses '-' instead of '+', '_' instead of '/'
*
* @param source the string to decode (decoded in default encoding)
* @return the decoded data
*/
public static byte[] decodeWebSafe(byte[] source)
throws Base64DecoderException {
return decodeWebSafe(source, 0, source.length);
}
/**
* Decodes Base64 content in byte array format and returns
* the decoded byte array.
*
* @param source the Base64 encoded data
* @param off the offset of where to begin decoding
* @param len the length of characters to decode
* @return decoded data
* @since 1.3
* @throws Base64DecoderException
*/
public static byte[] decode(byte[] source, int off, int len)
throws Base64DecoderException {
return decode(source, off, len, DECODABET);
}
/**
* Decodes web safe Base64 content in byte array format and returns
* the decoded byte array.
* Web safe encoding uses '-' instead of '+', '_' instead of '/'
*
* @param source the Base64 encoded data
* @param off the offset of where to begin decoding
* @param len the length of characters to decode
* @return decoded data
*/
public static byte[] decodeWebSafe(byte[] source, int off, int len)
throws Base64DecoderException {
return decode(source, off, len, WEBSAFE_DECODABET);
}
/**
* Decodes Base64 content using the supplied decodabet and returns
* the decoded byte array.
*
* @param source the Base64 encoded data
* @param off the offset of where to begin decoding
* @param len the length of characters to decode
* @param decodabet the decodabet for decoding Base64 content
* @return decoded data
*/
public static byte[] decode(byte[] source, int off, int len, byte[] decodabet)
throws Base64DecoderException {
int len34 = len * 3 / 4;
byte[] outBuff = new byte[2 + len34]; // Upper limit on size of output
int outBuffPosn = 0;
byte[] b4 = new byte[4];
int b4Posn = 0;
int i = 0;
byte sbiCrop = 0;
byte sbiDecode = 0;
for (i = 0; i < len; i++) {
sbiCrop = (byte) (source[i + off] & 0x7f); // Only the low seven bits
sbiDecode = decodabet[sbiCrop];
if (sbiDecode >= WHITE_SPACE_ENC) { // White space Equals sign or better
if (sbiDecode >= EQUALS_SIGN_ENC) {
// An equals sign (for padding) must not occur at position 0 or 1
// and must be the last byte[s] in the encoded value
if (sbiCrop == EQUALS_SIGN) {
int bytesLeft = len - i;
byte lastByte = (byte) (source[len - 1 + off] & 0x7f);
if (b4Posn == 0 || b4Posn == 1) {
throw new Base64DecoderException(
"invalid padding byte '=' at byte offset " + i);
} else if ((b4Posn == 3 && bytesLeft > 2)
|| (b4Posn == 4 && bytesLeft > 1)) {
throw new Base64DecoderException(
"padding byte '=' falsely signals end of encoded value "
+ "at offset " + i);
} else if (lastByte != EQUALS_SIGN && lastByte != NEW_LINE) {
throw new Base64DecoderException(
"encoded value has invalid trailing byte");
}
break;
}
b4[b4Posn++] = sbiCrop;
if (b4Posn == 4) {
outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet);
b4Posn = 0;
}
}
} else {
throw new Base64DecoderException("Bad Base64 input character at " + i
+ ": " + source[i + off] + "(decimal)");
}
}
// Because web safe encoding allows non padding base64 encodes, we
// need to pad the rest of the b4 buffer with equal signs when
// b4Posn != 0. There can be at most 2 equal signs at the end of
// four characters, so the b4 buffer must have two or three
// characters. This also catches the case where the input is
// padded with EQUALS_SIGN
if (b4Posn != 0) {
if (b4Posn == 1) {
throw new Base64DecoderException("single trailing character at offset "
+ (len - 1));
}
b4[b4Posn++] = EQUALS_SIGN;
outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet);
}
byte[] out = new byte[outBuffPosn];
System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
return out;
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.
*/
package net.robotmedia.billing.utils;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
/**
* An obfuscator that uses AES to encrypt data.
*/
public class AESObfuscator {
private static final String UTF8 = "UTF-8";
private static final String KEYGEN_ALGORITHM = "PBEWITHSHAAND256BITAES-CBC-BC";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final byte[] IV =
{ 16, 74, 71, -80, 32, 101, -47, 72, 117, -14, 0, -29, 70, 65, -12, 74 };
private static final String header = "net.robotmedia.billing.utils.AESObfuscator-1|";
private Cipher mEncryptor;
private Cipher mDecryptor;
public AESObfuscator(byte[] salt, String password) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
KeySpec keySpec =
new PBEKeySpec(password.toCharArray(), salt, 1024, 256);
SecretKey tmp = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
} catch (GeneralSecurityException e) {
// This can't happen on a compatible Android device.
throw new RuntimeException("Invalid environment", e);
}
}
public String obfuscate(String original) {
if (original == null) {
return null;
}
try {
// Header is appended as an integrity check
return Base64.encode(mEncryptor.doFinal((header + original).getBytes(UTF8)));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Invalid environment", e);
} catch (GeneralSecurityException e) {
throw new RuntimeException("Invalid environment", e);
}
}
public String unobfuscate(String obfuscated) throws ValidationException {
if (obfuscated == null) {
return null;
}
try {
String result = new String(mDecryptor.doFinal(Base64.decode(obfuscated)), UTF8);
// Check for presence of header. This serves as a final integrity check, for cases
// where the block size is correct during decryption.
int headerIndex = result.indexOf(header);
if (headerIndex != 0) {
throw new ValidationException("Header not found (invalid data or key)" + ":" +
obfuscated);
}
return result.substring(header.length(), result.length());
} catch (Base64DecoderException e) {
throw new ValidationException(e.getMessage() + ":" + obfuscated);
} catch (IllegalBlockSizeException e) {
throw new ValidationException(e.getMessage() + ":" + obfuscated);
} catch (BadPaddingException e) {
throw new ValidationException(e.getMessage() + ":" + obfuscated);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Invalid environment", e);
}
}
public class ValidationException extends Exception {
public ValidationException() {
super();
}
public ValidationException(String s) {
super(s);
}
private static final long serialVersionUID = 1L;
}
} | Java |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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.
*/
package net.robotmedia.billing.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.content.IntentSender;
import android.util.Log;
public class Compatibility {
private static Method startIntentSender;
public static int START_NOT_STICKY;
@SuppressWarnings("rawtypes")
private static final Class[] START_INTENT_SENDER_SIG = new Class[] {
IntentSender.class, Intent.class, int.class, int.class, int.class
};
static {
initCompatibility();
};
private static void initCompatibility() {
try {
final Field field = Service.class.getField("START_NOT_STICKY");
START_NOT_STICKY = field.getInt(null);
} catch (Exception e) {
START_NOT_STICKY = 2;
}
try {
startIntentSender = Activity.class.getMethod("startIntentSender",
START_INTENT_SENDER_SIG);
} catch (SecurityException e) {
startIntentSender = null;
} catch (NoSuchMethodException e) {
startIntentSender = null;
}
}
public static void startIntentSender(Activity activity, IntentSender intentSender, Intent intent) {
if (startIntentSender != null) {
final Object[] args = new Object[5];
args[0] = intentSender;
args[1] = intent;
args[2] = Integer.valueOf(0);
args[3] = Integer.valueOf(0);
args[4] = Integer.valueOf(0);
try {
startIntentSender.invoke(activity, args);
} catch (Exception e) {
Log.e(Compatibility.class.getSimpleName(), "startIntentSender", e);
}
}
}
public static boolean isStartIntentSenderSupported() {
return startIntentSender != null;
}
}
| Java |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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.
*/
package net.robotmedia.billing.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;
import android.content.Context;
public class Installation {
private static final String INSTALLATION = "INSTALLATION";
private static String sID = null;
public synchronized static String id(Context context) {
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists()) {
writeInstallationFile(installation);
}
sID = readInstallationFile(installation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return sID;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
| Java |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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.
*/
package net.robotmedia.billing;
import android.app.PendingIntent;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import com.android.vending.billing.IMarketBillingService;
public abstract class BillingRequest {
public static class CheckBillingSupported extends BillingRequest {
public CheckBillingSupported(String packageName, int startId) {
super(packageName, startId);
}
@Override
public String getRequestType() {
return "CHECK_BILLING_SUPPORTED";
}
@Override
protected void processOkResponse(Bundle response) {
final boolean supported = this.isSuccess();
BillingController.onBillingChecked(supported);
}
}
public static class ConfirmNotifications extends BillingRequest {
private String[] notifyIds;
private static final String KEY_NOTIFY_IDS = "NOTIFY_IDS";
public ConfirmNotifications(String packageName, int startId, String[] notifyIds) {
super(packageName, startId);
this.notifyIds = notifyIds;
}
@Override
protected void addParams(Bundle request) {
request.putStringArray(KEY_NOTIFY_IDS, notifyIds);
}
@Override
public String getRequestType() {
return "CONFIRM_NOTIFICATIONS";
}
}
public static class GetPurchaseInformation extends BillingRequest {
private String[] notifyIds;
private static final String KEY_NOTIFY_IDS = "NOTIFY_IDS";
public GetPurchaseInformation(String packageName, int startId, String[] notifyIds) {
super(packageName,startId);
this.notifyIds = notifyIds;
}
@Override
protected void addParams(Bundle request) {
request.putStringArray(KEY_NOTIFY_IDS, notifyIds);
}
@Override
public String getRequestType() {
return "GET_PURCHASE_INFORMATION";
}
@Override public boolean hasNonce() { return true; }
}
public static class RequestPurchase extends BillingRequest {
private String itemId;
private String developerPayload;
private static final String KEY_ITEM_ID = "ITEM_ID";
private static final String KEY_DEVELOPER_PAYLOAD = "DEVELOPER_PAYLOAD";
private static final String KEY_PURCHASE_INTENT = "PURCHASE_INTENT";
public RequestPurchase(String packageName, int startId, String itemId, String developerPayload) {
super(packageName, startId);
this.itemId = itemId;
this.developerPayload = developerPayload;
}
@Override
protected void addParams(Bundle request) {
request.putString(KEY_ITEM_ID, itemId);
if (developerPayload != null) {
request.putString(KEY_DEVELOPER_PAYLOAD, developerPayload);
}
}
@Override
public String getRequestType() {
return "REQUEST_PURCHASE";
}
@Override
public void onResponseCode(ResponseCode response) {
super.onResponseCode(response);
BillingController.onRequestPurchaseResponse(itemId, response);
}
@Override
protected void processOkResponse(Bundle response) {
final PendingIntent purchaseIntent = response.getParcelable(KEY_PURCHASE_INTENT);
BillingController.onPurchaseIntent(itemId, purchaseIntent);
}
}
public static enum ResponseCode {
RESULT_OK, // 0
RESULT_USER_CANCELED, // 1
RESULT_SERVICE_UNAVAILABLE, // 2
RESULT_BILLING_UNAVAILABLE, // 3
RESULT_ITEM_UNAVAILABLE, // 4
RESULT_DEVELOPER_ERROR, // 5
RESULT_ERROR; // 6
public static boolean isResponseOk(int response) {
return ResponseCode.RESULT_OK.ordinal() == response;
}
// Converts from an ordinal value to the ResponseCode
public static ResponseCode valueOf(int index) {
ResponseCode[] values = ResponseCode.values();
if (index < 0 || index >= values.length) {
return RESULT_ERROR;
}
return values[index];
}
}
public static class RestoreTransactions extends BillingRequest {
public RestoreTransactions(String packageName, int startId) {
super(packageName, startId);
}
@Override
public String getRequestType() {
return "RESTORE_TRANSACTIONS";
}
@Override public boolean hasNonce() { return true; }
@Override
public void onResponseCode(ResponseCode response) {
super.onResponseCode(response);
if (response == ResponseCode.RESULT_OK) {
BillingController.onTransactionsRestored();
}
}
}
private static final String KEY_BILLING_REQUEST = "BILLING_REQUEST";
private static final String KEY_API_VERSION = "API_VERSION";
private static final String KEY_PACKAGE_NAME = "PACKAGE_NAME";
private static final String KEY_RESPONSE_CODE = "RESPONSE_CODE";
protected static final String KEY_REQUEST_ID = "REQUEST_ID";
private static final String KEY_NONCE = "NONCE";
public static final long IGNORE_REQUEST_ID = -1;
private String packageName;
private int startId;
private boolean success;
private long nonce;
public BillingRequest(String packageName,int startId) {
this.packageName = packageName;
this.startId=startId;
}
protected void addParams(Bundle request) {
// Do nothing by default
}
public long getNonce() {
return nonce;
}
public abstract String getRequestType();
public boolean hasNonce() {
return false;
}
public boolean isSuccess() {
return success;
}
protected Bundle makeRequestBundle() {
final Bundle request = new Bundle();
request.putString(KEY_BILLING_REQUEST, getRequestType());
request.putInt(KEY_API_VERSION, 1);
request.putString(KEY_PACKAGE_NAME, packageName);
if (hasNonce()) {
request.putLong(KEY_NONCE, nonce);
}
return request;
}
public void onResponseCode(ResponseCode responde) {
// Do nothing by default
}
protected void processOkResponse(Bundle response) {
// Do nothing by default
}
public long run(IMarketBillingService mService) throws RemoteException {
final Bundle request = makeRequestBundle();
addParams(request);
final Bundle response = mService.sendBillingRequest(request);
if (validateResponse(response)) {
processOkResponse(response);
return response.getLong(KEY_REQUEST_ID, IGNORE_REQUEST_ID);
} else {
return IGNORE_REQUEST_ID;
}
}
public void setNonce(long nonce) {
this.nonce = nonce;
}
protected boolean validateResponse(Bundle response) {
final int responseCode = response.getInt(KEY_RESPONSE_CODE);
success = ResponseCode.isResponseOk(responseCode);
if (!success) {
Log.w(this.getClass().getSimpleName(), "Error with response code " + ResponseCode.valueOf(responseCode));
}
return success;
}
public int getStartId() {
return startId;
}
} | Java |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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.
*/
package net.robotmedia.billing;
import net.robotmedia.billing.BillingRequest.ResponseCode;
import net.robotmedia.billing.model.Transaction.PurchaseState;
import android.app.PendingIntent;
public interface IBillingObserver {
/**
* Called only once after determining if in-app billing is supported or not.
*
* @param supported
* if true, in-app billing is supported. Otherwise, it isn't.
* @see BillingController#checkBillingSupported(android.content.Context)
*/
public void onBillingChecked(boolean supported);
/**
* Called after requesting the purchase of the specified item.
*
* @param itemId
* id of the item whose purchase was requested.
* @param purchaseIntent
* a purchase pending intent for the specified item.
* @see BillingController#requestPurchase(android.content.Context, String,
* boolean)
*/
public void onPurchaseIntent(String itemId, PendingIntent purchaseIntent);
/**
* Called when the specified item is purchased, cancelled or refunded.
*
* @param itemId
* id of the item whose purchase state has changed.
* @param state
* purchase state of the specified item.
*/
public void onPurchaseStateChanged(String itemId, PurchaseState state);
/**
* Called with the response for the purchase request of the specified item.
* This is used for reporting various errors, or if the user backed out and
* didn't purchase the item.
*
* @param itemId
* id of the item whose purchase was requested
* @param response
* response of the purchase request
*/
public void onRequestPurchaseResponse(String itemId, ResponseCode response);
/**
* Called when a restore transactions request has been successfully
* received by the server.
*/
public void onTransactionsRestored();
}
| Java |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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.
*/
package net.robotmedia.billing;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import net.robotmedia.billing.model.Transaction;
import net.robotmedia.billing.model.TransactionManager;
import net.robotmedia.billing.security.DefaultSignatureValidator;
import net.robotmedia.billing.security.ISignatureValidator;
import net.robotmedia.billing.utils.Compatibility;
import net.robotmedia.billing.utils.Security;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
public class BillingController {
public static enum BillingStatus {
UNKNOWN, SUPPORTED, UNSUPPORTED
}
/**
* Used to provide on-demand values to the billing controller.
*/
public interface IConfiguration {
/**
* Returns a salt for the obfuscation of purchases in local memory.
*
* @return array of 20 random bytes.
*/
public byte[] getObfuscationSalt();
/**
* Returns the public key used to verify the signature of responses of
* the Market Billing service.
*
* @return Base64 encoded public key.
*/
public String getPublicKey();
}
private static BillingStatus status = BillingStatus.UNKNOWN;
private static Set<String> automaticConfirmations = new HashSet<String>();
private static IConfiguration configuration = null;
private static boolean debug = false;
private static ISignatureValidator validator = null;
private static final String JSON_NONCE = "nonce";
private static final String JSON_ORDERS = "orders";
private static HashMap<String, Set<String>> manualConfirmations = new HashMap<String, Set<String>>();
private static Set<IBillingObserver> observers = new HashSet<IBillingObserver>();
public static final String LOG_TAG = "Billing";
private static HashMap<Long, BillingRequest> pendingRequests = new HashMap<Long, BillingRequest>();
/**
* Adds the specified notification to the set of manual confirmations of the
* specified item.
*
* @param itemId
* id of the item.
* @param notificationId
* id of the notification.
*/
private static final void addManualConfirmation(String itemId, String notificationId) {
Set<String> notifications = manualConfirmations.get(itemId);
if (notifications == null) {
notifications = new HashSet<String>();
manualConfirmations.put(itemId, notifications);
}
notifications.add(notificationId);
}
/**
* Returns the billing status. If it is currently unknown, checks the billing
* status asynchronously, in which case observers will eventually receive
* a {@link IBillingObserver#onBillingChecked(boolean)} notification.
*
* @param context
* @return the current billing status (unknown, supported or unsupported).
* @see IBillingObserver#onBillingChecked(boolean)
*/
public static BillingStatus checkBillingSupported(Context context) {
if (status == BillingStatus.UNKNOWN) {
BillingService.checkBillingSupported(context);
}
return status;
}
/**
* Requests to confirm all pending notifications for the specified item.
*
* @param context
* @param itemId
* id of the item whose purchase must be confirmed.
* @return true if pending notifications for this item were found, false
* otherwise.
*/
public static boolean confirmNotifications(Context context, String itemId) {
final Set<String> notifications = manualConfirmations.get(itemId);
if (notifications != null) {
confirmNotifications(context, notifications.toArray(new String[] {}));
return true;
} else {
return false;
}
}
/**
* Requests to confirm all specified notifications.
*
* @param context
* @param notifyIds
* array with the ids of all the notifications to confirm.
*/
private static void confirmNotifications(Context context, String[] notifyIds) {
BillingService.confirmNotifications(context, notifyIds);
}
/**
* Returns the number of purchases for the specified item. Refunded and
* cancelled purchases are not subtracted. See
* {@link #countPurchasesNet(Context, String)} if they need to be.
*
* @param context
* @param itemId
* id of the item whose purchases will be counted.
* @return number of purchases for the specified item.
*/
public static int countPurchases(Context context, String itemId) {
final byte[] salt = getSalt();
itemId = salt != null ? Security.obfuscate(context, salt, itemId) : itemId;
return TransactionManager.countPurchases(context, itemId);
}
protected static void debug(String message) {
if (debug) {
Log.d(LOG_TAG, message);
}
}
/**
* Requests purchase information for the specified notification. Immediately
* followed by a call to
* {@link #onPurchaseInformationResponse(long, boolean)} and later to
* {@link #onPurchaseStateChanged(Context, String, String)}, if the request
* is successful.
*
* @param context
* @param notifyId
* id of the notification whose purchase information is
* requested.
*/
private static void getPurchaseInformation(Context context, String notifyId) {
final long nonce = Security.generateNonce();
BillingService.getPurchaseInformation(context, new String[] { notifyId }, nonce);
}
/**
* Gets the salt from the configuration and logs a warning if it's null.
*
* @return salt.
*/
private static byte[] getSalt() {
byte[] salt = null;
if (configuration == null || ((salt = configuration.getObfuscationSalt()) == null)) {
Log.w(LOG_TAG, "Can't (un)obfuscate purchases without salt");
}
return salt;
}
/**
* Lists all transactions stored locally, including cancellations and
* refunds.
*
* @param context
* @return list of transactions.
*/
public static List<Transaction> getTransactions(Context context) {
List<Transaction> transactions = TransactionManager.getTransactions(context);
unobfuscate(context, transactions);
return transactions;
}
/**
* Lists all transactions of the specified item, stored locally.
*
* @param context
* @param itemId
* id of the item whose transactions will be returned.
* @return list of transactions.
*/
public static List<Transaction> getTransactions(Context context, String itemId) {
final byte[] salt = getSalt();
itemId = salt != null ? Security.obfuscate(context, salt, itemId) : itemId;
List<Transaction> transactions = TransactionManager.getTransactions(context, itemId);
unobfuscate(context, transactions);
return transactions;
}
/**
* Returns true if the specified item has been registered as purchased in
* local memory. Note that if the item was later canceled or refunded this
* will still return true. Also note that the item might have been purchased
* in another installation, but not yet registered in this one.
*
* @param context
* @param itemId
* item id.
* @return true if the specified item is purchased, false otherwise.
*/
public static boolean isPurchased(Context context, String itemId) {
final byte[] salt = getSalt();
itemId = salt != null ? Security.obfuscate(context, salt, itemId) : itemId;
return TransactionManager.isPurchased(context, itemId);
}
/**
* Notifies observers of the purchase state change of the specified item.
*
* @param itemId
* id of the item whose purchase state has changed.
* @param state
* new purchase state of the item.
*/
private static void notifyPurchaseStateChange(String itemId, Transaction.PurchaseState state) {
for (IBillingObserver o : observers) {
o.onPurchaseStateChanged(itemId, state);
}
}
/**
* Obfuscates the specified purchase. Only the order id, product id and
* developer payload are obfuscated.
*
* @param context
* @param purchase
* purchase to be obfuscated.
* @see #unobfuscate(Context, Transaction)
*/
static void obfuscate(Context context, Transaction purchase) {
final byte[] salt = getSalt();
if (salt == null) {
return;
}
purchase.orderId = Security.obfuscate(context, salt, purchase.orderId);
purchase.productId = Security.obfuscate(context, salt, purchase.productId);
purchase.developerPayload = Security.obfuscate(context, salt, purchase.developerPayload);
}
/**
* Called after the response to a
* {@link net.robotmedia.billing.request.CheckBillingSupported} request is
* received.
*
* @param supported
*/
protected static void onBillingChecked(boolean supported) {
status = supported ? BillingStatus.SUPPORTED : BillingStatus.UNSUPPORTED;
for (IBillingObserver o : observers) {
o.onBillingChecked(supported);
}
}
/**
* Called when an IN_APP_NOTIFY message is received.
*
* @param context
* @param notifyId
* notification id.
*/
protected static void onNotify(Context context, String notifyId) {
debug("Notification " + notifyId + " available");
getPurchaseInformation(context, notifyId);
}
/**
* Called after the response to a
* {@link net.robotmedia.billing.request.RequestPurchase} request is
* received.
*
* @param itemId
* id of the item whose purchase was requested.
* @param purchaseIntent
* intent to purchase the item.
*/
protected static void onPurchaseIntent(String itemId, PendingIntent purchaseIntent) {
for (IBillingObserver o : observers) {
o.onPurchaseIntent(itemId, purchaseIntent);
}
}
/**
* Called after the response to a
* {@link net.robotmedia.billing.request.GetPurchaseInformation} request is
* received. Registers all transactions in local memory and confirms those
* who can be confirmed automatically.
*
* @param context
* @param signedData
* signed JSON data received from the Market Billing service.
* @param signature
* data signature.
*/
protected static void onPurchaseStateChanged(Context context, String signedData, String signature) {
debug("Purchase state changed");
if (TextUtils.isEmpty(signedData)) {
Log.w(LOG_TAG, "Signed data is empty");
return;
}
if (!debug) {
if (TextUtils.isEmpty(signature)) {
Log.w(LOG_TAG, "Empty signature requires debug mode");
return;
}
final ISignatureValidator validator = BillingController.validator != null ? BillingController.validator
: new DefaultSignatureValidator(BillingController.configuration);
if (!validator.validate(signedData, signature)) {
Log.w(LOG_TAG, "Signature does not match data.");
return;
}
}
List<Transaction> purchases;
try {
JSONObject jObject = new JSONObject(signedData);
if (!verifyNonce(jObject)) {
Log.w(LOG_TAG, "Invalid nonce");
return;
}
purchases = parsePurchases(jObject);
} catch (JSONException e) {
Log.e(LOG_TAG, "JSON exception: ", e);
return;
}
ArrayList<String> confirmations = new ArrayList<String>();
for (Transaction p : purchases) {
if (p.notificationId != null && automaticConfirmations.contains(p.productId)) {
confirmations.add(p.notificationId);
} else {
// TODO: Discriminate between purchases, cancellations and
// refunds.
addManualConfirmation(p.productId, p.notificationId);
}
storeTransaction(context, p);
notifyPurchaseStateChange(p.productId, p.purchaseState);
}
if (!confirmations.isEmpty()) {
final String[] notifyIds = confirmations.toArray(new String[confirmations.size()]);
confirmNotifications(context, notifyIds);
}
}
/**
* Called after a {@link net.robotmedia.billing.BillingRequest} is
* sent.
*
* @param requestId
* the id the request.
* @param request
* the billing request.
*/
protected static void onRequestSent(long requestId, BillingRequest request) {
debug("Request " + requestId + " of type " + request.getRequestType() + " sent");
if (request.isSuccess()) {
pendingRequests.put(requestId, request);
} else if (request.hasNonce()) {
Security.removeNonce(request.getNonce());
}
}
/**
* Called after a {@link net.robotmedia.billing.BillingRequest} is
* sent.
*
* @param context
* @param requestId
* the id of the request.
* @param responseCode
* the response code.
* @see net.robotmedia.billing.request.ResponseCode
*/
protected static void onResponseCode(Context context, long requestId, int responseCode) {
final BillingRequest.ResponseCode response = BillingRequest.ResponseCode.valueOf(responseCode);
debug("Request " + requestId + " received response " + response);
final BillingRequest request = pendingRequests.get(requestId);
if (request != null) {
pendingRequests.remove(requestId);
request.onResponseCode(response);
}
}
protected static void onTransactionsRestored() {
for (IBillingObserver o : observers) {
o.onTransactionsRestored();
}
}
/**
* Parse all purchases from the JSON data received from the Market Billing
* service.
*
* @param data
* JSON data received from the Market Billing service.
* @return list of purchases.
* @throws JSONException
* if the data couldn't be properly parsed.
*/
private static List<Transaction> parsePurchases(JSONObject data) throws JSONException {
ArrayList<Transaction> purchases = new ArrayList<Transaction>();
JSONArray orders = data.optJSONArray(JSON_ORDERS);
int numTransactions = 0;
if (orders != null) {
numTransactions = orders.length();
}
for (int i = 0; i < numTransactions; i++) {
JSONObject jElement = orders.getJSONObject(i);
Transaction p = Transaction.parse(jElement);
purchases.add(p);
}
return purchases;
}
/**
* Registers the specified billing observer.
*
* @param observer
* the billing observer to add.
* @return true if the observer wasn't previously registered, false
* otherwise.
* @see #unregisterObserver(IBillingObserver)
*/
public static boolean registerObserver(IBillingObserver observer) {
return observers.add(observer);
}
/**
* Requests the purchase of the specified item. The transaction will not be
* confirmed automatically.
*
* @param context
* @param itemId
* id of the item to be purchased.
* @see #requestPurchase(Context, String, boolean)
*/
public static void requestPurchase(Context context, String itemId) {
requestPurchase(context, itemId, false);
}
/**
* Requests the purchase of the specified item with optional automatic
* confirmation.
*
* @param context
* @param itemId
* id of the item to be purchased.
* @param confirm
* if true, the transaction will be confirmed automatically. If
* false, the transaction will have to be confirmed with a call
* to {@link #confirmNotifications(Context, String)}.
* @see IBillingObserver#onPurchaseIntent(String, PendingIntent)
*/
public static void requestPurchase(Context context, String itemId, boolean confirm) {
if (confirm) {
automaticConfirmations.add(itemId);
}
BillingService.requestPurchase(context, itemId, null);
}
/**
* Requests to restore all transactions.
*
* @param context
*/
public static void restoreTransactions(Context context) {
final long nonce = Security.generateNonce();
BillingService.restoreTransations(context, nonce);
}
/**
* Sets the configuration instance of the controller.
*
* @param config
* configuration instance.
*/
public static void setConfiguration(IConfiguration config) {
configuration = config;
}
/**
* Sets debug mode.
*
* @param value
*/
public static final void setDebug(boolean value) {
debug = value;
}
/**
* Sets a custom signature validator. If no custom signature validator is
* provided,
* {@link net.robotmedia.billing.signature.DefaultSignatureValidator} will
* be used.
*
* @param validator
* signature validator instance.
*/
public static void setSignatureValidator(ISignatureValidator validator) {
BillingController.validator = validator;
}
/**
* Starts the specified purchase intent with the specified activity.
*
* @param activity
* @param purchaseIntent
* purchase intent.
* @param intent
*/
public static void startPurchaseIntent(Activity activity, PendingIntent purchaseIntent, Intent intent) {
if (Compatibility.isStartIntentSenderSupported()) {
// This is on Android 2.0 and beyond. The in-app buy page activity
// must be on the activity stack of the application.
Compatibility.startIntentSender(activity, purchaseIntent.getIntentSender(), intent);
} else {
// This is on Android version 1.6. The in-app buy page activity must
// be on its own separate activity stack instead of on the activity
// stack of the application.
try {
purchaseIntent.send(activity, 0 /* code */, intent);
} catch (CanceledException e) {
Log.e(LOG_TAG, "Error starting purchase intent", e);
}
}
}
static void storeTransaction(Context context, Transaction t) {
final Transaction t2 = t.clone();
obfuscate(context, t2);
TransactionManager.addTransaction(context, t2);
}
static void unobfuscate(Context context, List<Transaction> transactions) {
for (Transaction p : transactions) {
unobfuscate(context, p);
}
}
/**
* Unobfuscate the specified purchase.
*
* @param context
* @param purchase
* purchase to unobfuscate.
* @see #obfuscate(Context, Transaction)
*/
static void unobfuscate(Context context, Transaction purchase) {
final byte[] salt = getSalt();
if (salt == null) {
return;
}
purchase.orderId = Security.unobfuscate(context, salt, purchase.orderId);
purchase.productId = Security.unobfuscate(context, salt, purchase.productId);
purchase.developerPayload = Security.unobfuscate(context, salt, purchase.developerPayload);
}
/**
* Unregisters the specified billing observer.
*
* @param observer
* the billing observer to unregister.
* @return true if the billing observer was unregistered, false otherwise.
* @see #registerObserver(IBillingObserver)
*/
public static boolean unregisterObserver(IBillingObserver observer) {
return observers.remove(observer);
}
private static boolean verifyNonce(JSONObject data) {
long nonce = data.optLong(JSON_NONCE);
if (Security.isNonceKnown(nonce)) {
Security.removeNonce(nonce);
return true;
} else {
return false;
}
}
protected static void onRequestPurchaseResponse(String itemId, BillingRequest.ResponseCode response) {
for (IBillingObserver o : observers) {
o.onRequestPurchaseResponse(itemId, response);
}
}
}
| Java |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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.
*/
package net.robotmedia.billing.model;
import java.util.ArrayList;
import java.util.List;
import net.robotmedia.billing.model.Transaction.PurchaseState;
import android.content.Context;
import android.database.Cursor;
public class TransactionManager {
public synchronized static void addTransaction(Context context, Transaction transaction) {
BillingDB db = new BillingDB(context);
db.insert(transaction);
db.close();
}
public synchronized static boolean isPurchased(Context context, String itemId) {
return countPurchases(context, itemId) > 0;
}
public synchronized static int countPurchases(Context context, String itemId) {
BillingDB db = new BillingDB(context);
final Cursor c = db.queryTransactions(itemId, PurchaseState.PURCHASED);
int count = 0;
if (c != null) {
count = c.getCount();
c.close();
}
db.close();
return count;
}
public synchronized static List<Transaction> getTransactions(Context context) {
BillingDB db = new BillingDB(context);
final Cursor c = db.queryTransactions();
final List<Transaction> transactions = cursorToList(c);
db.close();
return transactions;
}
private static List<Transaction> cursorToList(final Cursor c) {
final List<Transaction> transactions = new ArrayList<Transaction>();
if (c != null) {
while (c.moveToNext()) {
final Transaction purchase = BillingDB.createTransaction(c);
transactions.add(purchase);
}
c.close();
}
return transactions;
}
public synchronized static List<Transaction> getTransactions(Context context, String itemId) {
BillingDB db = new BillingDB(context);
final Cursor c = db.queryTransactions(itemId);
final List<Transaction> transactions = cursorToList(c);
db.close();
return transactions;
}
}
| Java |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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.
*/
package net.robotmedia.billing.model;
import net.robotmedia.billing.model.Transaction.PurchaseState;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class BillingDB {
static final String DATABASE_NAME = "billing.db";
static final int DATABASE_VERSION = 1;
static final String TABLE_TRANSACTIONS = "purchases";
public static final String COLUMN__ID = "_id";
public static final String COLUMN_STATE = "state";
public static final String COLUMN_PRODUCT_ID = "productId";
public static final String COLUMN_PURCHASE_TIME = "purchaseTime";
public static final String COLUMN_DEVELOPER_PAYLOAD = "developerPayload";
private static final String[] TABLE_TRANSACTIONS_COLUMNS = {
COLUMN__ID, COLUMN_PRODUCT_ID, COLUMN_STATE,
COLUMN_PURCHASE_TIME, COLUMN_DEVELOPER_PAYLOAD
};
SQLiteDatabase mDb;
private DatabaseHelper mDatabaseHelper;
public BillingDB(Context context) {
mDatabaseHelper = new DatabaseHelper(context);
mDb = mDatabaseHelper.getWritableDatabase();
}
public void close() {
mDatabaseHelper.close();
}
public void insert(Transaction transaction) {
ContentValues values = new ContentValues();
values.put(COLUMN__ID, transaction.orderId);
values.put(COLUMN_PRODUCT_ID, transaction.productId);
values.put(COLUMN_STATE, transaction.purchaseState.ordinal());
values.put(COLUMN_PURCHASE_TIME, transaction.purchaseTime);
values.put(COLUMN_DEVELOPER_PAYLOAD, transaction.developerPayload);
mDb.replace(TABLE_TRANSACTIONS, null /* nullColumnHack */, values);
}
public Cursor queryTransactions() {
return mDb.query(TABLE_TRANSACTIONS, TABLE_TRANSACTIONS_COLUMNS, null,
null, null, null, null);
}
public Cursor queryTransactions(String productId) {
return mDb.query(TABLE_TRANSACTIONS, TABLE_TRANSACTIONS_COLUMNS, COLUMN_PRODUCT_ID + " = ?",
new String[] {productId}, null, null, null);
}
public Cursor queryTransactions(String productId, PurchaseState state) {
return mDb.query(TABLE_TRANSACTIONS, TABLE_TRANSACTIONS_COLUMNS, COLUMN_PRODUCT_ID + " = ? AND " + COLUMN_STATE + " = ?",
new String[] {productId, String.valueOf(state.ordinal())}, null, null, null);
}
protected static final Transaction createTransaction(Cursor cursor) {
final Transaction purchase = new Transaction();
purchase.orderId = cursor.getString(0);
purchase.productId = cursor.getString(1);
purchase.purchaseState = PurchaseState.valueOf(cursor.getInt(2));
purchase.purchaseTime = cursor.getLong(3);
purchase.developerPayload = cursor.getString(4);
return purchase;
}
private class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
createTransactionsTable(db);
}
private void createTransactionsTable(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_TRANSACTIONS + "(" +
COLUMN__ID + " TEXT PRIMARY KEY, " +
COLUMN_PRODUCT_ID + " INTEGER, " +
COLUMN_STATE + " TEXT, " +
COLUMN_PURCHASE_TIME + " TEXT, " +
COLUMN_DEVELOPER_PAYLOAD + " INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}
}
| Java |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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.
*/
package net.robotmedia.billing.model;
import org.json.JSONException;
import org.json.JSONObject;
public class Transaction {
public enum PurchaseState {
// Responses to requestPurchase or restoreTransactions.
PURCHASED, // 0: User was charged for the order.
CANCELLED, // 1: The charge failed on the server.
REFUNDED; // 2: User received a refund for the order.
// Converts from an ordinal value to the PurchaseState
public static PurchaseState valueOf(int index) {
PurchaseState[] values = PurchaseState.values();
if (index < 0 || index >= values.length) {
return CANCELLED;
}
return values[index];
}
}
static final String DEVELOPER_PAYLOAD = "developerPayload";
static final String NOTIFICATION_ID = "notificationId";
static final String ORDER_ID = "orderId";
static final String PACKAGE_NAME = "packageName";
static final String PRODUCT_ID = "productId";
static final String PURCHASE_STATE = "purchaseState";
static final String PURCHASE_TIME = "purchaseTime";
public static Transaction parse(JSONObject json) throws JSONException {
final Transaction transaction = new Transaction();
final int response = json.getInt(PURCHASE_STATE);
transaction.purchaseState = PurchaseState.valueOf(response);
transaction.productId = json.getString(PRODUCT_ID);
transaction.packageName = json.getString(PACKAGE_NAME);
transaction.purchaseTime = json.getLong(PURCHASE_TIME);
transaction.orderId = json.optString(ORDER_ID, null);
transaction.notificationId = json.optString(NOTIFICATION_ID, null);
transaction.developerPayload = json.optString(DEVELOPER_PAYLOAD, null);
return transaction;
}
public String developerPayload;
public String notificationId;
public String orderId;
public String packageName;
public String productId;
public PurchaseState purchaseState;
public long purchaseTime;
public Transaction() {}
public Transaction(String orderId, String productId, String packageName, PurchaseState purchaseState,
String notificationId, long purchaseTime, String developerPayload) {
this.orderId = orderId;
this.productId = productId;
this.packageName = packageName;
this.purchaseState = purchaseState;
this.notificationId = notificationId;
this.purchaseTime = purchaseTime;
this.developerPayload = developerPayload;
}
public Transaction clone() {
return new Transaction(orderId, productId, packageName, purchaseState, notificationId, purchaseTime, developerPayload);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Transaction other = (Transaction) obj;
if (developerPayload == null) {
if (other.developerPayload != null)
return false;
} else if (!developerPayload.equals(other.developerPayload))
return false;
if (notificationId == null) {
if (other.notificationId != null)
return false;
} else if (!notificationId.equals(other.notificationId))
return false;
if (orderId == null) {
if (other.orderId != null)
return false;
} else if (!orderId.equals(other.orderId))
return false;
if (packageName == null) {
if (other.packageName != null)
return false;
} else if (!packageName.equals(other.packageName))
return false;
if (productId == null) {
if (other.productId != null)
return false;
} else if (!productId.equals(other.productId))
return false;
if (purchaseState != other.purchaseState)
return false;
if (purchaseTime != other.purchaseTime)
return false;
return true;
}
@Override
public String toString() {
return String.valueOf(orderId);
}
}
| Java |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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.
*/
package net.robotmedia.billing.helper;
import net.robotmedia.billing.BillingController;
import net.robotmedia.billing.BillingController.BillingStatus;
import net.robotmedia.billing.BillingRequest.ResponseCode;
import net.robotmedia.billing.model.Transaction.PurchaseState;
import android.app.Activity;
public abstract class AbstractBillingActivity extends Activity implements BillingController.IConfiguration {
protected AbstractBillingObserver mBillingObserver;
/**
* Returns the billing status. If it's currently unknown, requests to check
* if billing is supported and
* {@link AbstractBillingActivity#onBillingChecked(boolean)} should be
* called later with the result.
*
* @return the current billing status (unknown, supported or unsupported).
* @see AbstractBillingActivity#onBillingChecked(boolean)
*/
public BillingStatus checkBillingSupported() {
return BillingController.checkBillingSupported(this);
}
public abstract void onBillingChecked(boolean supported);
@Override
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBillingObserver = new AbstractBillingObserver(this) {
@Override
public void onBillingChecked(boolean supported) {
AbstractBillingActivity.this.onBillingChecked(supported);
}
@Override
public void onPurchaseStateChanged(String itemId, PurchaseState state) {
AbstractBillingActivity.this.onPurchaseStateChanged(itemId, state);
}
@Override
public void onRequestPurchaseResponse(String itemId, ResponseCode response) {
AbstractBillingActivity.this.onRequestPurchaseResponse(itemId, response);
}
};
BillingController.registerObserver(mBillingObserver);
BillingController.setConfiguration(this); // This activity will provide
// the public key and salt
this.checkBillingSupported();
if (!mBillingObserver.isTransactionsRestored()) {
BillingController.restoreTransactions(this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
BillingController.unregisterObserver(mBillingObserver); // Avoid
// receiving
// notifications after
// destroy
BillingController.setConfiguration(null);
}
public abstract void onPurchaseStateChanged(String itemId, PurchaseState state);;
public abstract void onRequestPurchaseResponse(String itemId, ResponseCode response);
/**
* Requests the purchase of the specified item. The transaction will not be
* confirmed automatically; such confirmation could be handled in
* {@link AbstractBillingActivity#onPurchaseExecuted(String)}. If automatic
* confirmation is preferred use
* {@link BillingController#requestPurchase(android.content.Context, String, boolean)}
* instead.
*
* @param itemId
* id of the item to be purchased.
*/
public void requestPurchase(String itemId) {
BillingController.requestPurchase(this, itemId);
}
/**
* Requests to restore all transactions.
*/
public void restoreTransactions() {
BillingController.restoreTransactions(this);
}
}
| Java |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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.
*/
package net.robotmedia.billing.helper;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import net.robotmedia.billing.BillingController;
import net.robotmedia.billing.IBillingObserver;
/**
* Abstract subclass of IBillingObserver that provides default implementations
* for {@link IBillingObserver#onPurchaseIntent(String, PendingIntent)} and
* {@link IBillingObserver#onTransactionsRestored()}.
*
*/
public abstract class AbstractBillingObserver implements IBillingObserver {
protected static final String KEY_TRANSACTIONS_RESTORED = "net.robotmedia.billing.transactionsRestored";
protected Activity activity;
public AbstractBillingObserver(Activity activity) {
this.activity = activity;
}
public boolean isTransactionsRestored() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
return preferences.getBoolean(KEY_TRANSACTIONS_RESTORED, false);
}
/**
* Called after requesting the purchase of the specified item. The default
* implementation simply starts the pending intent.
*
* @param itemId
* id of the item whose purchase was requested.
* @param purchaseIntent
* a purchase pending intent for the specified item.
*/
@Override
public void onPurchaseIntent(String itemId, PendingIntent purchaseIntent) {
BillingController.startPurchaseIntent(activity, purchaseIntent, null);
}
@Override
public void onTransactionsRestored() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
final Editor editor = preferences.edit();
editor.putBoolean(KEY_TRANSACTIONS_RESTORED, true);
editor.commit();
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.