Ejemplo n.º 1
0
 public void testEquals_immutableMultiset() {
   Collection<String> c = ImmutableSortedMultiset.of("a", "b", "a");
   assertEquals(c, ImmutableSortedMultiset.of("a", "b", "a"));
   assertEquals(c, ImmutableSortedMultiset.of("a", "a", "b"));
   ASSERT.that(c).isNotEqualTo(ImmutableSortedMultiset.of("a", "b"));
   ASSERT.that(c).isNotEqualTo(ImmutableSortedMultiset.of("a", "b", "c", "d"));
 }
Ejemplo n.º 2
0
 public void testAsList() {
   ImmutableSortedMultiset<String> multiset = ImmutableSortedMultiset.of("a", "a", "b", "b", "b");
   ImmutableList<String> list = multiset.asList();
   assertEquals(ImmutableList.of("a", "a", "b", "b", "b"), list);
   assertTrue(list instanceof ImmutableAsList);
   ImmutableList<String> copy = SerializableTester.reserializeAndAssert(list);
   assertTrue(copy instanceof ImmutableAsList);
   assertEquals(2, list.indexOf("b"));
   assertEquals(4, list.lastIndexOf("b"));
 }
Ejemplo n.º 3
0
 private static boolean resultsMatch(
     QueryResult controlResult, QueryResult testResult, int precision) {
   SortedMultiset<List<Object>> control =
       ImmutableSortedMultiset.copyOf(rowComparator(precision), controlResult.getResults());
   SortedMultiset<List<Object>> test =
       ImmutableSortedMultiset.copyOf(rowComparator(precision), testResult.getResults());
   try {
     return control.equals(test);
   } catch (TypesDoNotMatchException e) {
     return false;
   }
 }
Ejemplo n.º 4
0
 public void testBuilderAddAllMultiset() {
   Multiset<String> a = HashMultiset.create(asList("a", "b", "b"));
   Multiset<String> b = HashMultiset.create(asList("c", "b"));
   ImmutableSortedMultiset<String> multiset =
       ImmutableSortedMultiset.<String>naturalOrder().addAll(a).addAll(b).build();
   assertEquals(HashMultiset.create(asList("a", "b", "b", "b", "c")), multiset);
 }
Ejemplo n.º 5
0
 public void testCreation_arrayContainingOnlyNull() {
   String[] array = new String[] {null};
   try {
     ImmutableSortedMultiset.copyOf(array);
     fail();
   } catch (NullPointerException expected) {
   }
 }
Ejemplo n.º 6
0
 public void testBuilderSetCountIllegal() {
   ImmutableSortedMultiset.Builder<String> builder = ImmutableSortedMultiset.naturalOrder();
   try {
     builder.setCount("a", -2);
     fail("expected IllegalArgumentException");
   } catch (IllegalArgumentException expected) {
   }
 }
Ejemplo n.º 7
0
 public void testCopyOf_iteratorContainingNull() {
   Iterator<String> iterator = asList("a", null, "b").iterator();
   try {
     ImmutableSortedMultiset.copyOf(iterator);
     fail();
   } catch (NullPointerException expected) {
   }
 }
Ejemplo n.º 8
0
 public void testCopyOf_multisetContainingNull() {
   Multiset<String> c = HashMultiset.create(asList("a", null, "b"));
   try {
     ImmutableSortedMultiset.copyOf(c);
     fail();
   } catch (NullPointerException expected) {
   }
 }
Ejemplo n.º 9
0
 public void testCopyOf_collectionContainingNull() {
   Collection<String> c = MinimalCollection.of("a", null, "b");
   try {
     ImmutableSortedMultiset.copyOf(c);
     fail();
   } catch (NullPointerException expected) {
   }
 }
Ejemplo n.º 10
0
 public void testBuilderAddCopiesHandlesNullsCorrectly() {
   ImmutableSortedMultiset.Builder<String> builder = ImmutableSortedMultiset.naturalOrder();
   try {
     builder.addCopies(null, 2);
     fail("expected NullPointerException");
   } catch (NullPointerException expected) {
   }
 }
Ejemplo n.º 11
0
 /**
  * Returns an immutable sorted multiset containing the given elements sorted by the given {@code
  * Comparator}. This method iterates over {@code elements} at most once.
  *
  * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
  * safe to do so. The exact circumstances under which a copy will or will not be performed are
  * undocumented and subject to change.
  *
  * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
  */
 public static <E> ImmutableSortedMultiset<E> copyOf(
     Comparator<? super E> comparator, Iterable<? extends E> elements) {
   if (elements instanceof ImmutableSortedMultiset) {
     @SuppressWarnings("unchecked") // immutable collections are always safe for covariant casts
     ImmutableSortedMultiset<E> multiset = (ImmutableSortedMultiset<E>) elements;
     if (comparator.equals(multiset.comparator())) {
       if (multiset.isPartialView()) {
         return copyOfSortedEntries(comparator, multiset.entrySet().asList());
       } else {
         return multiset;
       }
     }
   }
   elements = Lists.newArrayList(elements); // defensive copy
   TreeMultiset<E> sortedCopy = TreeMultiset.create(checkNotNull(comparator));
   Iterables.addAll(sortedCopy, elements);
   return copyOfSortedEntries(comparator, sortedCopy.entrySet());
 }
Ejemplo n.º 12
0
 public void testBuilderSetCount() {
   ImmutableSortedMultiset<String> multiset =
       ImmutableSortedMultiset.<String>naturalOrder()
           .add("a")
           .setCount("a", 2)
           .setCount("b", 3)
           .build();
   assertEquals(HashMultiset.create(asList("a", "a", "b", "b", "b")), multiset);
 }
Ejemplo n.º 13
0
  public String getResultsComparison(int precision) {
    List<List<Object>> controlResults = controlResult.getResults();
    List<List<Object>> testResults = testResult.getResults();

    if (valid() || (controlResults == null) || (testResults == null)) {
      return "";
    }

    Multiset<List<Object>> control =
        ImmutableSortedMultiset.copyOf(rowComparator(precision), controlResults);
    Multiset<List<Object>> test =
        ImmutableSortedMultiset.copyOf(rowComparator(precision), testResults);

    try {
      Iterable<ChangedRow> diff =
          ImmutableSortedMultiset.<ChangedRow>naturalOrder()
              .addAll(
                  Iterables.transform(
                      Multisets.difference(control, test),
                      row -> new ChangedRow(Changed.REMOVED, row, precision)))
              .addAll(
                  Iterables.transform(
                      Multisets.difference(test, control),
                      row -> new ChangedRow(Changed.ADDED, row, precision)))
              .build();
      diff = Iterables.limit(diff, 100);

      StringBuilder sb = new StringBuilder();

      sb.append(format("Control %s rows, Test %s rows%n", control.size(), test.size()));
      if (verboseResultsComparison) {
        Joiner.on("\n").appendTo(sb, diff);
      } else {
        sb.append("RESULTS DO NOT MATCH\n");
      }

      return sb.toString();
    } catch (TypesDoNotMatchException e) {
      return e.getMessage();
    }
  }
Ejemplo n.º 14
0
  public void testBuilderAddAllHandlesNullsCorrectly() {
    ImmutableSortedMultiset.Builder<String> builder = ImmutableSortedMultiset.naturalOrder();
    try {
      builder.addAll((Collection<String>) null);
      fail("expected NullPointerException");
    } catch (NullPointerException expected) {
    }

    builder = ImmutableSortedMultiset.naturalOrder();
    List<String> listWithNulls = asList("a", null, "b");
    try {
      builder.addAll(listWithNulls);
      fail("expected NullPointerException");
    } catch (NullPointerException expected) {
    }

    builder = ImmutableSortedMultiset.naturalOrder();
    Multiset<String> multisetWithNull = LinkedHashMultiset.create(asList("a", null, "b"));
    try {
      builder.addAll(multisetWithNull);
      fail("expected NullPointerException");
    } catch (NullPointerException expected) {
    }
  }
Ejemplo n.º 15
0
 public void testCreation_arrayOfArray() {
   Comparator<String[]> comparator =
       Ordering.natural()
           .lexicographical()
           .onResultOf(
               new Function<String[], Iterable<Comparable>>() {
                 @Override
                 public Iterable<Comparable> apply(String[] input) {
                   return Arrays.<Comparable>asList(input);
                 }
               });
   String[] array = new String[] {"a"};
   Multiset<String[]> multiset = ImmutableSortedMultiset.orderedBy(comparator).add(array).build();
   Multiset<String[]> expected = HashMultiset.create();
   expected.add(array);
   assertEquals(expected, multiset);
 }
Ejemplo n.º 16
0
 public void testCopyOf_iterator_empty() {
   Iterator<String> iterator = Iterators.emptyIterator();
   Multiset<String> multiset = ImmutableSortedMultiset.copyOf(iterator);
   assertTrue(multiset.isEmpty());
 }
Ejemplo n.º 17
0
 public void testSerialization_entrySet() {
   Multiset<String> c = ImmutableSortedMultiset.of("a", "b", "c");
   SerializableTester.reserializeAndAssert(c.entrySet());
 }
Ejemplo n.º 18
0
 public void testCreation_noArgs() {
   Multiset<String> multiset = ImmutableSortedMultiset.of();
   assertTrue(multiset.isEmpty());
 }
Ejemplo n.º 19
0
 public void testCreation_oneElement() {
   Multiset<String> multiset = ImmutableSortedMultiset.of("a");
   assertEquals(HashMultiset.create(asList("a")), multiset);
 }
Ejemplo n.º 20
0
 public void testMultisetWrites() {
   Multiset<String> multiset = ImmutableSortedMultiset.of("a", "b", "a");
   UnmodifiableCollectionTests.assertMultisetIsUnmodifiable(multiset, "test");
 }
Ejemplo n.º 21
0
 public void testCopyOf_iterator_oneElement() {
   Iterator<String> iterator = Iterators.singletonIterator("a");
   Multiset<String> multiset = ImmutableSortedMultiset.copyOf(iterator);
   assertEquals(HashMultiset.create(asList("a")), multiset);
 }
Ejemplo n.º 22
0
 public void testBuilderAddAllIterator() {
   Iterator<String> iterator = asList("a", "b", "a", "c").iterator();
   ImmutableSortedMultiset<String> multiset =
       ImmutableSortedMultiset.<String>naturalOrder().addAll(iterator).build();
   assertEquals(HashMultiset.create(asList("a", "b", "a", "c")), multiset);
 }
Ejemplo n.º 23
0
 public void testIterationOrder() {
   Collection<String> c = ImmutableSortedMultiset.of("a", "b", "a");
   ASSERT.that(c).hasContentsInOrder("a", "a", "b");
 }
Ejemplo n.º 24
0
/**
 * Supplies an arbitrary "default" instance for a wide range of types, often useful in testing
 * utilities.
 *
 * <p>Covers arrays, enums and common types defined in {@code java.lang}, {@code java.lang.reflect},
 * {@code java.io}, {@code java.nio}, {@code java.math}, {@code java.util}, {@code
 * java.util.concurrent}, {@code java.util.regex}, {@code com.google.common.base}, {@code
 * com.google.common.collect} and {@code com.google.common.primitives}. In addition, if the type
 * exposes at least one public static final constant of the same type, one of the constants will be
 * used; or if the class exposes a public parameter-less constructor then it will be "new"d and
 * returned.
 *
 * <p>All default instances returned by {@link #get} are generics-safe. Clients won't get type
 * errors for using {@code get(Comparator.class)} as a {@code Comparator<Foo>}, for example.
 * Immutable empty instances are returned for collection types; {@code ""} for string; {@code 0} for
 * number types; reasonable default instance for other stateless types. For mutable types, a fresh
 * instance is created each time {@code get()} is called.
 *
 * @author Kevin Bourrillion
 * @author Ben Yu
 * @since 12.0
 */
@Beta
public final class ArbitraryInstances {

  private static final Ordering<Field> BY_FIELD_NAME =
      new Ordering<Field>() {
        @Override
        public int compare(Field left, Field right) {
          return left.getName().compareTo(right.getName());
        }
      };

  /**
   * Returns a new {@code MatchResult} that corresponds to a successful match. Apache Harmony (used
   * in Android) requires a successful match in order to generate a {@code MatchResult}:
   * http://goo.gl/5VQFmC
   */
  private static MatchResult newMatchResult() {
    Matcher matcher = Pattern.compile(".").matcher("X");
    matcher.find();
    return matcher.toMatchResult();
  }

  private static final ClassToInstanceMap<Object> DEFAULTS =
      ImmutableClassToInstanceMap.builder()
          // primitives
          .put(Object.class, "")
          .put(Number.class, 0)
          .put(UnsignedInteger.class, UnsignedInteger.ZERO)
          .put(UnsignedLong.class, UnsignedLong.ZERO)
          .put(BigInteger.class, BigInteger.ZERO)
          .put(BigDecimal.class, BigDecimal.ZERO)
          .put(CharSequence.class, "")
          .put(String.class, "")
          .put(Pattern.class, Pattern.compile(""))
          .put(MatchResult.class, newMatchResult())
          .put(TimeUnit.class, TimeUnit.SECONDS)
          .put(Charset.class, Charsets.UTF_8)
          .put(Currency.class, Currency.getInstance(Locale.US))
          .put(Locale.class, Locale.US)
          // common.base
          .put(CharMatcher.class, CharMatcher.NONE)
          .put(Joiner.class, Joiner.on(','))
          .put(Splitter.class, Splitter.on(','))
          .put(Optional.class, Optional.absent())
          .put(Predicate.class, Predicates.alwaysTrue())
          .put(Equivalence.class, Equivalence.equals())
          .put(Ticker.class, Ticker.systemTicker())
          .put(Stopwatch.class, Stopwatch.createUnstarted())
          // io types
          .put(InputStream.class, new ByteArrayInputStream(new byte[0]))
          .put(ByteArrayInputStream.class, new ByteArrayInputStream(new byte[0]))
          .put(Readable.class, new StringReader(""))
          .put(Reader.class, new StringReader(""))
          .put(StringReader.class, new StringReader(""))
          .put(Buffer.class, ByteBuffer.allocate(0))
          .put(CharBuffer.class, CharBuffer.allocate(0))
          .put(ByteBuffer.class, ByteBuffer.allocate(0))
          .put(ShortBuffer.class, ShortBuffer.allocate(0))
          .put(IntBuffer.class, IntBuffer.allocate(0))
          .put(LongBuffer.class, LongBuffer.allocate(0))
          .put(FloatBuffer.class, FloatBuffer.allocate(0))
          .put(DoubleBuffer.class, DoubleBuffer.allocate(0))
          .put(File.class, new File(""))
          .put(ByteSource.class, ByteSource.empty())
          .put(CharSource.class, CharSource.empty())
          .put(ByteSink.class, NullByteSink.INSTANCE)
          .put(CharSink.class, NullByteSink.INSTANCE.asCharSink(Charsets.UTF_8))
          // All collections are immutable empty. So safe for any type parameter.
          .put(Iterator.class, ImmutableSet.of().iterator())
          .put(PeekingIterator.class, Iterators.peekingIterator(ImmutableSet.of().iterator()))
          .put(ListIterator.class, ImmutableList.of().listIterator())
          .put(Iterable.class, ImmutableSet.of())
          .put(Collection.class, ImmutableList.of())
          .put(ImmutableCollection.class, ImmutableList.of())
          .put(List.class, ImmutableList.of())
          .put(ImmutableList.class, ImmutableList.of())
          .put(Set.class, ImmutableSet.of())
          .put(ImmutableSet.class, ImmutableSet.of())
          .put(SortedSet.class, ImmutableSortedSet.of())
          .put(ImmutableSortedSet.class, ImmutableSortedSet.of())
          .put(NavigableSet.class, Sets.unmodifiableNavigableSet(Sets.newTreeSet()))
          .put(Map.class, ImmutableMap.of())
          .put(ImmutableMap.class, ImmutableMap.of())
          .put(SortedMap.class, ImmutableSortedMap.of())
          .put(ImmutableSortedMap.class, ImmutableSortedMap.of())
          .put(NavigableMap.class, Maps.unmodifiableNavigableMap(Maps.newTreeMap()))
          .put(Multimap.class, ImmutableMultimap.of())
          .put(ImmutableMultimap.class, ImmutableMultimap.of())
          .put(ListMultimap.class, ImmutableListMultimap.of())
          .put(ImmutableListMultimap.class, ImmutableListMultimap.of())
          .put(SetMultimap.class, ImmutableSetMultimap.of())
          .put(ImmutableSetMultimap.class, ImmutableSetMultimap.of())
          .put(
              SortedSetMultimap.class,
              Multimaps.unmodifiableSortedSetMultimap(TreeMultimap.create()))
          .put(Multiset.class, ImmutableMultiset.of())
          .put(ImmutableMultiset.class, ImmutableMultiset.of())
          .put(SortedMultiset.class, ImmutableSortedMultiset.of())
          .put(ImmutableSortedMultiset.class, ImmutableSortedMultiset.of())
          .put(BiMap.class, ImmutableBiMap.of())
          .put(ImmutableBiMap.class, ImmutableBiMap.of())
          .put(Table.class, ImmutableTable.of())
          .put(ImmutableTable.class, ImmutableTable.of())
          .put(RowSortedTable.class, Tables.unmodifiableRowSortedTable(TreeBasedTable.create()))
          .put(ClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build())
          .put(ImmutableClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build())
          .put(Comparable.class, ByToString.INSTANCE)
          .put(Comparator.class, AlwaysEqual.INSTANCE)
          .put(Ordering.class, AlwaysEqual.INSTANCE)
          .put(Range.class, Range.all())
          .put(MapConstraint.class, MapConstraints.notNull())
          .put(MapDifference.class, Maps.difference(ImmutableMap.of(), ImmutableMap.of()))
          .put(
              SortedMapDifference.class,
              Maps.difference(ImmutableSortedMap.of(), ImmutableSortedMap.of()))
          // reflect
          .put(AnnotatedElement.class, Object.class)
          .put(GenericDeclaration.class, Object.class)
          .put(Type.class, Object.class)
          .build();

  /**
   * type -> implementation. Inherently mutable interfaces and abstract classes are mapped to their
   * default implementations and are "new"d upon get().
   */
  private static final ConcurrentMap<Class<?>, Class<?>> implementations = Maps.newConcurrentMap();

  private static <T> void setImplementation(Class<T> type, Class<? extends T> implementation) {
    checkArgument(type != implementation, "Don't register %s to itself!", type);
    checkArgument(
        !DEFAULTS.containsKey(type), "A default value was already registered for %s", type);
    checkArgument(
        implementations.put(type, implementation) == null,
        "Implementation for %s was already registered",
        type);
  }

  static {
    setImplementation(Appendable.class, StringBuilder.class);
    setImplementation(BlockingQueue.class, LinkedBlockingDeque.class);
    setImplementation(BlockingDeque.class, LinkedBlockingDeque.class);
    setImplementation(ConcurrentMap.class, ConcurrentHashMap.class);
    setImplementation(ConcurrentNavigableMap.class, ConcurrentSkipListMap.class);
    setImplementation(CountDownLatch.class, Dummies.DummyCountDownLatch.class);
    setImplementation(Deque.class, ArrayDeque.class);
    setImplementation(OutputStream.class, ByteArrayOutputStream.class);
    setImplementation(PrintStream.class, Dummies.InMemoryPrintStream.class);
    setImplementation(PrintWriter.class, Dummies.InMemoryPrintWriter.class);
    setImplementation(Queue.class, ArrayDeque.class);
    setImplementation(Random.class, Dummies.DeterministicRandom.class);
    setImplementation(
        ScheduledThreadPoolExecutor.class, Dummies.DummyScheduledThreadPoolExecutor.class);
    setImplementation(ThreadPoolExecutor.class, Dummies.DummyScheduledThreadPoolExecutor.class);
    setImplementation(Writer.class, StringWriter.class);
    setImplementation(Runnable.class, Dummies.DummyRunnable.class);
    setImplementation(ThreadFactory.class, Dummies.DummyThreadFactory.class);
    setImplementation(Executor.class, Dummies.DummyExecutor.class);
  }

  @SuppressWarnings("unchecked") // it's a subtype map
  @Nullable
  private static <T> Class<? extends T> getImplementation(Class<T> type) {
    return (Class<? extends T>) implementations.get(type);
  }

  private static final Logger logger = Logger.getLogger(ArbitraryInstances.class.getName());

  /**
   * Returns an arbitrary instance for {@code type}, or {@code null} if no arbitrary instance can be
   * determined.
   */
  @Nullable
  public static <T> T get(Class<T> type) {
    T defaultValue = DEFAULTS.getInstance(type);
    if (defaultValue != null) {
      return defaultValue;
    }
    Class<? extends T> implementation = getImplementation(type);
    if (implementation != null) {
      return get(implementation);
    }
    if (type.isEnum()) {
      T[] enumConstants = type.getEnumConstants();
      return (enumConstants.length == 0) ? null : enumConstants[0];
    }
    if (type.isArray()) {
      return createEmptyArray(type);
    }
    T jvmDefault = Defaults.defaultValue(Primitives.unwrap(type));
    if (jvmDefault != null) {
      return jvmDefault;
    }
    if (Modifier.isAbstract(type.getModifiers()) || !Modifier.isPublic(type.getModifiers())) {
      return arbitraryConstantInstanceOrNull(type);
    }
    final Constructor<T> constructor;
    try {
      constructor = type.getConstructor();
    } catch (NoSuchMethodException e) {
      return arbitraryConstantInstanceOrNull(type);
    }
    constructor.setAccessible(true); // accessibility check is too slow
    try {
      return constructor.newInstance();
    } catch (InstantiationException impossible) {
      throw new AssertionError(impossible);
    } catch (IllegalAccessException impossible) {
      throw new AssertionError(impossible);
    } catch (InvocationTargetException e) {
      logger.log(Level.WARNING, "Exception while invoking default constructor.", e.getCause());
      return arbitraryConstantInstanceOrNull(type);
    }
  }

  @Nullable
  private static <T> T arbitraryConstantInstanceOrNull(Class<T> type) {
    Field[] fields = type.getDeclaredFields();
    Arrays.sort(fields, BY_FIELD_NAME);
    for (Field field : fields) {
      if (Modifier.isPublic(field.getModifiers())
          && Modifier.isStatic(field.getModifiers())
          && Modifier.isFinal(field.getModifiers())) {
        if (field.getGenericType() == field.getType() && type.isAssignableFrom(field.getType())) {
          field.setAccessible(true);
          try {
            T constant = type.cast(field.get(null));
            if (constant != null) {
              return constant;
            }
          } catch (IllegalAccessException impossible) {
            throw new AssertionError(impossible);
          }
        }
      }
    }
    return null;
  }

  private static <T> T createEmptyArray(Class<T> arrayType) {
    return arrayType.cast(Array.newInstance(arrayType.getComponentType(), 0));
  }

  // Internal implementations of some classes, with public default constructor that get() needs.
  private static final class Dummies {

    public static final class InMemoryPrintStream extends PrintStream {
      public InMemoryPrintStream() {
        super(new ByteArrayOutputStream());
      }
    }

    public static final class InMemoryPrintWriter extends PrintWriter {
      public InMemoryPrintWriter() {
        super(new StringWriter());
      }
    }

    public static final class DeterministicRandom extends Random {
      public DeterministicRandom() {
        super(0);
      }
    }

    public static final class DummyScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
      public DummyScheduledThreadPoolExecutor() {
        super(1);
      }
    }

    public static final class DummyCountDownLatch extends CountDownLatch {
      public DummyCountDownLatch() {
        super(0);
      }
    }

    public static final class DummyRunnable implements Runnable, Serializable {
      @Override
      public void run() {}
    }

    public static final class DummyThreadFactory implements ThreadFactory, Serializable {
      @Override
      public Thread newThread(Runnable r) {
        return new Thread(r);
      }
    }

    public static final class DummyExecutor implements Executor, Serializable {
      @Override
      public void execute(Runnable command) {}
    }
  }

  private static final class NullByteSink extends ByteSink implements Serializable {
    private static final NullByteSink INSTANCE = new NullByteSink();

    @Override
    public OutputStream openStream() {
      return ByteStreams.nullOutputStream();
    }
  }

  // Compare by toString() to satisfy 2 properties:
  // 1. compareTo(null) should throw NullPointerException
  // 2. the order is deterministic and easy to understand, for debugging purpose.
  private static final class ByToString implements Comparable<Object>, Serializable {
    private static final ByToString INSTANCE = new ByToString();

    @Override
    public int compareTo(Object o) {
      return toString().compareTo(o.toString());
    }

    @Override
    public String toString() {
      return "BY_TO_STRING";
    }

    private Object readResolve() {
      return INSTANCE;
    }
  }

  // Always equal is a valid total ordering. And it works for any Object.
  private static final class AlwaysEqual extends Ordering<Object> implements Serializable {
    private static final AlwaysEqual INSTANCE = new AlwaysEqual();

    @Override
    public int compare(Object o1, Object o2) {
      return 0;
    }

    @Override
    public String toString() {
      return "ALWAYS_EQUAL";
    }

    private Object readResolve() {
      return INSTANCE;
    }
  }

  private ArbitraryInstances() {}
}
Ejemplo n.º 25
0
 public void testSerialization_elementSet() {
   Multiset<String> c = ImmutableSortedMultiset.of("a", "b", "a");
   Collection<String> copy = SerializableTester.reserializeAndAssert(c.elementSet());
   ASSERT.that(copy).hasContentsInOrder("a", "b");
 }
Ejemplo n.º 26
0
 public void testSerialization_empty() {
   Collection<String> c = ImmutableSortedMultiset.of();
   assertSame(c, SerializableTester.reserialize(c));
 }
Ejemplo n.º 27
0
 public void testCopyOf_plainIterable() {
   CountingIterable iterable = new CountingIterable();
   Multiset<String> multiset = ImmutableSortedMultiset.copyOf(iterable);
   assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset);
   assertEquals(1, iterable.count);
 }
Ejemplo n.º 28
0
 public void testCopyOf_shortcut_singleton() {
   Collection<String> c = ImmutableSortedMultiset.of("a");
   assertSame(c, ImmutableSortedMultiset.copyOf(c));
 }
Ejemplo n.º 29
0
 public void testCopyOf_iterator_general() {
   Iterator<String> iterator = asList("a", "b", "a").iterator();
   Multiset<String> multiset = ImmutableSortedMultiset.copyOf(iterator);
   assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset);
 }
Ejemplo n.º 30
0
 public void testCopyOf_shortcut_immutableMultiset() {
   Collection<String> c = ImmutableSortedMultiset.of("a", "b", "c");
   assertSame(c, ImmutableSortedMultiset.copyOf(c));
 }