001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect.testing;
018
019import com.google.common.annotations.GwtCompatible;
020import java.util.ArrayList;
021import java.util.Arrays;
022import java.util.Collection;
023import java.util.List;
024import java.util.Set;
025
026/**
027 * A simplistic set which implements the bare minimum so that it can be used in tests without
028 * relying on any specific Set implementations. Slow. Explicitly allows null elements so that they
029 * can be used in the testers.
030 *
031 * @author Regina O'Dell
032 */
033@GwtCompatible
034public class MinimalSet<E> extends MinimalCollection<E> implements Set<E> {
035
036  @SuppressWarnings("unchecked") // empty Object[] as E[]
037  public static <E> MinimalSet<E> of(E... contents) {
038    return ofClassAndContents(Object.class, (E[]) new Object[0], Arrays.asList(contents));
039  }
040
041  @SuppressWarnings("unchecked") // empty Object[] as E[]
042  public static <E> MinimalSet<E> from(Collection<? extends E> contents) {
043    return ofClassAndContents(Object.class, (E[]) new Object[0], contents);
044  }
045
046  public static <E> MinimalSet<E> ofClassAndContents(
047      Class<? super E> type, E[] emptyArrayForContents, Iterable<? extends E> contents) {
048    List<E> setContents = new ArrayList<E>();
049    for (E e : contents) {
050      if (!setContents.contains(e)) {
051        setContents.add(e);
052      }
053    }
054    return new MinimalSet<E>(type, setContents.toArray(emptyArrayForContents));
055  }
056
057  private MinimalSet(Class<? super E> type, E... contents) {
058    super(type, true, contents);
059  }
060
061  /*
062   * equals() and hashCode() are more specific in the Set contract.
063   */
064
065  @Override
066  public boolean equals(Object object) {
067    if (object instanceof Set) {
068      Set<?> that = (Set<?>) object;
069      return (this.size() == that.size()) && this.containsAll(that);
070    }
071    return false;
072  }
073
074  @Override
075  public int hashCode() {
076    int hashCodeSum = 0;
077    for (Object o : this) {
078      hashCodeSum += (o == null) ? 0 : o.hashCode();
079    }
080    return hashCodeSum;
081  }
082}