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