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; 025import org.checkerframework.checker.nullness.qual.Nullable; 026 027/** 028 * A simplistic set which implements the bare minimum so that it can be used in tests without 029 * relying on any specific Set implementations. Slow. Explicitly allows null elements so that they 030 * can be used in the testers. 031 * 032 * @author Regina O'Dell 033 */ 034@GwtCompatible 035public class MinimalSet<E> extends MinimalCollection<E> implements Set<E> { 036 037 @SuppressWarnings("unchecked") // empty Object[] as E[] 038 public static <E> MinimalSet<E> of(E... contents) { 039 return ofClassAndContents(Object.class, (E[]) new Object[0], Arrays.asList(contents)); 040 } 041 042 @SuppressWarnings("unchecked") // empty Object[] as E[] 043 public static <E> MinimalSet<E> from(Collection<? extends E> contents) { 044 return ofClassAndContents(Object.class, (E[]) new Object[0], contents); 045 } 046 047 public static <E> MinimalSet<E> ofClassAndContents( 048 Class<? super E> type, E[] emptyArrayForContents, Iterable<? extends E> contents) { 049 List<E> setContents = new ArrayList<>(); 050 for (E e : contents) { 051 if (!setContents.contains(e)) { 052 setContents.add(e); 053 } 054 } 055 return new MinimalSet<>(type, setContents.toArray(emptyArrayForContents)); 056 } 057 058 private MinimalSet(Class<? super E> type, E... contents) { 059 super(type, true, contents); 060 } 061 062 /* 063 * equals() and hashCode() are more specific in the Set contract. 064 */ 065 066 @Override 067 public boolean equals(@Nullable Object object) { 068 if (object instanceof Set) { 069 Set<?> that = (Set<?>) object; 070 return (this.size() == that.size()) && this.containsAll(that); 071 } 072 return false; 073 } 074 075 @Override 076 public int hashCode() { 077 int hashCodeSum = 0; 078 for (Object o : this) { 079 hashCodeSum += (o == null) ? 0 : o.hashCode(); 080 } 081 return hashCodeSum; 082 } 083}