Home | History | Annotate | Download | only in collect
      1 /*
      2  * Copyright (C) 2007 The Guava Authors
      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 com.google.common.collect;
     18 
     19 import com.google.common.annotations.GwtCompatible;
     20 import com.google.common.annotations.VisibleForTesting;
     21 import com.google.common.collect.ImmutableSet.ArrayImmutableSet;
     22 
     23 /**
     24  * Implementation of {@link ImmutableSet} with two or more elements.
     25  *
     26  * @author Kevin Bourrillion
     27  */
     28 @GwtCompatible(serializable = true, emulated = true)
     29 @SuppressWarnings("serial") // uses writeReplace(), not default serialization
     30 final class RegularImmutableSet<E> extends ArrayImmutableSet<E> {
     31   // the same elements in hashed positions (plus nulls)
     32   @VisibleForTesting final transient Object[] table;
     33   // 'and' with an int to get a valid table index.
     34   private final transient int mask;
     35   private final transient int hashCode;
     36 
     37   RegularImmutableSet(
     38       Object[] elements, int hashCode, Object[] table, int mask) {
     39     super(elements);
     40     this.table = table;
     41     this.mask = mask;
     42     this.hashCode = hashCode;
     43   }
     44 
     45   @Override public boolean contains(Object target) {
     46     if (target == null) {
     47       return false;
     48     }
     49     for (int i = Hashing.smear(target.hashCode()); true; i++) {
     50       Object candidate = table[i & mask];
     51       if (candidate == null) {
     52         return false;
     53       }
     54       if (candidate.equals(target)) {
     55         return true;
     56       }
     57     }
     58   }
     59 
     60   @Override public int hashCode() {
     61     return hashCode;
     62   }
     63 
     64   @Override boolean isHashCodeFast() {
     65     return true;
     66   }
     67 }
     68