Home | History | Annotate | Download | only in util
      1 /*
      2  * Copyright (C) 2011 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package android.util;
     18 
     19 import java.util.AbstractSet;
     20 import java.util.Iterator;
     21 
     22 /**
     23  * A fast immutable set wrapper for an array that is optimized for non-concurrent iteration.
     24  * The same iterator instance is reused each time to avoid creating lots of garbage.
     25  * Iterating over an array in this fashion is 2.5x faster than iterating over a {@link HashSet}
     26  * so it is worth copying the contents of the set to an array when iterating over it
     27  * hundreds of times.
     28  * @hide
     29  */
     30 public final class FastImmutableArraySet<T> extends AbstractSet<T> {
     31     FastIterator<T> mIterator;
     32     T[] mContents;
     33 
     34     public FastImmutableArraySet(T[] contents) {
     35         mContents = contents;
     36     }
     37 
     38     @Override
     39     public Iterator<T> iterator() {
     40         FastIterator<T> it = mIterator;
     41         if (it == null) {
     42             it = new FastIterator<T>(mContents);
     43             mIterator = it;
     44         } else {
     45             it.mIndex = 0;
     46         }
     47         return it;
     48     }
     49 
     50     @Override
     51     public int size() {
     52         return mContents.length;
     53     }
     54 
     55     private static final class FastIterator<T> implements Iterator<T> {
     56         private final T[] mContents;
     57         int mIndex;
     58 
     59         public FastIterator(T[] contents) {
     60             mContents = contents;
     61         }
     62 
     63         @Override
     64         public boolean hasNext() {
     65             return mIndex != mContents.length;
     66         }
     67 
     68         @Override
     69         public T next() {
     70             return mContents[mIndex++];
     71         }
     72 
     73         @Override
     74         public void remove() {
     75             throw new UnsupportedOperationException();
     76         }
     77     }
     78 }
     79