1/*
2 * Copyright (C) 2009 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.testing;
18
19import java.util.ArrayList;
20import java.util.Arrays;
21import java.util.Collection;
22import java.util.List;
23import java.util.Set;
24
25/**
26 * A simplistic set which implements the bare minimum so that it can be used in
27 * tests without relying on any specific Set implementations. Slow. Explicitly
28 * allows null elements so that they can be used in the testers.
29 *
30 * <p>This class is GWT compatible.
31 *
32 * @author Regina O'Dell
33 */
34public class MinimalSet<E> extends MinimalCollection<E> implements Set<E> {
35
36  @SuppressWarnings("unchecked") // empty Object[] as E[]
37  public static <E> MinimalSet<E> of(E... contents) {
38    return ofClassAndContents(
39        Object.class, (E[]) new Object[0], Arrays.asList(contents));
40  }
41
42  @SuppressWarnings("unchecked") // empty Object[] as E[]
43  public static <E> MinimalSet<E> from(Collection<? extends E> contents) {
44    return ofClassAndContents(Object.class, (E[]) new Object[0], contents);
45  }
46
47  public static <E> MinimalSet<E> ofClassAndContents(
48      Class<? super E> type, E[] emptyArrayForContents,
49      Iterable<? extends E> contents) {
50    List<E> setContents = new ArrayList<E>();
51    for (E e : contents) {
52      if (!setContents.contains(e)) {
53        setContents.add(e);
54      }
55    }
56    return new MinimalSet<E>(type, setContents.toArray(emptyArrayForContents));
57  }
58
59  private MinimalSet(Class<? super E> type, E... contents) {
60    super(type, true, contents);
61  }
62
63  /*
64   * equals() and hashCode() are more specific in the Set contract.
65   */
66
67  @Override public boolean equals(Object object) {
68    if (object instanceof Set) {
69      Set<?> that = (Set<?>) object;
70      return (this.size() == that.size()) && this.containsAll(that);
71    }
72    return false;
73  }
74
75  @Override public int hashCode() {
76    int hashCodeSum = 0;
77    for (Object o : this) {
78      hashCodeSum += (o == null) ? 0 : o.hashCode();
79    }
80    return hashCodeSum;
81  }
82}
83