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
17package com.google.common.collect;
18
19import com.google.common.annotations.GwtCompatible;
20import com.google.common.base.Preconditions;
21
22import java.util.Set;
23
24import javax.annotation.Nullable;
25
26/**
27 * Implementation of {@link ImmutableSet} with exactly one element.
28 *
29 * @author Kevin Bourrillion
30 * @author Nick Kralevich
31 */
32@GwtCompatible(serializable = true, emulated = true)
33@SuppressWarnings("serial") // uses writeReplace(), not default serialization
34final class SingletonImmutableSet<E> extends ImmutableSet<E> {
35
36  final transient E element;
37  // This is transient because it will be recalculated on the first
38  // call to hashCode().
39  //
40  // A race condition is avoided since threads will either see that the value
41  // is zero and recalculate it themselves, or two threads will see it at
42  // the same time, and both recalculate it.  If the cachedHashCode is 0,
43  // it will always be recalculated, unfortunately.
44  private transient int cachedHashCode;
45
46  SingletonImmutableSet(E element) {
47    this.element = Preconditions.checkNotNull(element);
48  }
49
50  SingletonImmutableSet(E element, int hashCode) {
51    // Guaranteed to be non-null by the presence of the pre-computed hash code.
52    this.element = element;
53    cachedHashCode = hashCode;
54  }
55
56  @Override
57  public int size() {
58    return 1;
59  }
60
61  @Override public boolean isEmpty() {
62    return false;
63  }
64
65  @Override public boolean contains(Object target) {
66    return element.equals(target);
67  }
68
69  @Override public UnmodifiableIterator<E> iterator() {
70    return Iterators.singletonIterator(element);
71  }
72
73  @Override boolean isPartialView() {
74    return false;
75  }
76
77  @Override public Object[] toArray() {
78    return new Object[] { element };
79  }
80
81  @Override public <T> T[] toArray(T[] array) {
82    if (array.length == 0) {
83      array = ObjectArrays.newArray(array, 1);
84    } else if (array.length > 1) {
85      array[1] = null;
86    }
87    // Writes will produce ArrayStoreException when the toArray() doc requires.
88    Object[] objectArray = array;
89    objectArray[0] = element;
90    return array;
91  }
92
93  @Override public boolean equals(@Nullable Object object) {
94    if (object == this) {
95      return true;
96    }
97    if (object instanceof Set) {
98      Set<?> that = (Set<?>) object;
99      return that.size() == 1 && element.equals(that.iterator().next());
100    }
101    return false;
102  }
103
104  @Override public final int hashCode() {
105    // Racy single-check.
106    int code = cachedHashCode;
107    if (code == 0) {
108      cachedHashCode = code = element.hashCode();
109    }
110    return code;
111  }
112
113  @Override boolean isHashCodeFast() {
114    return cachedHashCode != 0;
115  }
116
117  @Override public String toString() {
118    String elementToString = element.toString();
119    return new StringBuilder(elementToString.length() + 2)
120        .append('[')
121        .append(elementToString)
122        .append(']')
123        .toString();
124  }
125}
126