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 22 /** 23 * Implementation of {@link ImmutableSet} with two or more elements. 24 * 25 * @author Kevin Bourrillion 26 */ 27 @GwtCompatible(serializable = true, emulated = true) 28 @SuppressWarnings("serial") // uses writeReplace(), not default serialization 29 final class RegularImmutableSet<E> extends ImmutableSet<E> { 30 private final Object[] elements; 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 this.elements = 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 61 public int size() { 62 return elements.length; 63 } 64 65 @SuppressWarnings("unchecked") // all elements are E's 66 @Override 67 public UnmodifiableIterator<E> iterator() { 68 return (UnmodifiableIterator<E>) Iterators.forArray(elements); 69 } 70 71 @Override 72 int copyIntoArray(Object[] dst, int offset) { 73 System.arraycopy(elements, 0, dst, offset, elements.length); 74 return offset + elements.length; 75 } 76 77 @Override 78 ImmutableList<E> createAsList() { 79 return new RegularImmutableAsList<E>(this, elements); 80 } 81 82 @Override 83 boolean isPartialView() { 84 return false; 85 } 86 87 @Override public int hashCode() { 88 return hashCode; 89 } 90 91 @Override boolean isHashCodeFast() { 92 return true; 93 } 94 } 95