Remove redundant type arguments
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / ImmutableOffsetMap.java
index f45bbf6f15add26144973ba772ea06bd69600df8..844086df746c1c314f3a2625dd1aa268543cc0ef 100644 (file)
@@ -7,10 +7,13 @@
  */
 package org.opendaylight.yangtools.util;
 
+import static com.google.common.base.Preconditions.checkArgument;
+import static java.util.Objects.requireNonNull;
+
 import com.google.common.annotations.Beta;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.UnmodifiableIterator;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
@@ -25,13 +28,18 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import javax.annotation.Nonnull;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * Implementation of the {@link Map} interface which stores a set of immutable mappings using a key-to-offset map and
  * a backing array. This is useful for situations where the same key set is shared across a multitude of maps, as this
  * class uses a global cache to share the key-to-offset mapping.
  *
+ * <p>
+ * In case the set of keys is statically known, you can use {@link ImmutableOffsetMapTemplate} to efficiently create
+ * {@link ImmutableOffsetMap} instances.
+ *
  * @param <K> the type of keys maintained by this map
  * @param <V> the type of mapped values
  */
@@ -40,13 +48,12 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
     static final class Ordered<K, V> extends ImmutableOffsetMap<K, V> {
         private static final long serialVersionUID = 1L;
 
-        Ordered(final Map<K, Integer> offsets, final V[] objects) {
+        Ordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
             super(offsets, objects);
         }
 
-        @Nonnull
         @Override
-        public MutableOffsetMap<K, V> toModifiableMap() {
+        public @NonNull MutableOffsetMap<K, V> toModifiableMap() {
             return MutableOffsetMap.orderedCopyOf(this);
         }
 
@@ -60,13 +67,12 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
     static final class Unordered<K, V> extends ImmutableOffsetMap<K, V> {
         private static final long serialVersionUID = 1L;
 
-        Unordered(final Map<K, Integer> offsets, final V[] objects) {
+        Unordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
             super(offsets, objects);
         }
 
-        @Nonnull
         @Override
-        public MutableOffsetMap<K, V> toModifiableMap() {
+        public @NonNull MutableOffsetMap<K, V> toModifiableMap() {
             return MutableOffsetMap.unorderedCopyOf(this);
         }
 
@@ -81,8 +87,8 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
 
     private static final long serialVersionUID = 1L;
 
-    private final transient Map<K, Integer> offsets;
-    private final transient V[] objects;
+    private final transient @NonNull ImmutableMap<K, Integer> offsets;
+    private final transient @NonNull V[] objects;
     private transient int hashCode;
 
     /**
@@ -92,56 +98,43 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
      * @param objects Array of value object, may not be null. The array is stored as is, the caller
      *              is responsible for ensuring its contents remain unmodified.
      */
-    ImmutableOffsetMap(@Nonnull final Map<K, Integer> offsets, @Nonnull final V[] objects) {
-        this.offsets = Preconditions.checkNotNull(offsets);
-        this.objects = Preconditions.checkNotNull(objects);
-        Preconditions.checkArgument(offsets.size() == objects.length);
+    ImmutableOffsetMap(final ImmutableMap<K, Integer> offsets, final V[] objects) {
+        this.offsets = requireNonNull(offsets);
+        this.objects = requireNonNull(objects);
+        checkArgument(offsets.size() == objects.length);
     }
 
-    @Nonnull
     @Override
-    public abstract MutableOffsetMap<K, V> toModifiableMap();
+    public abstract @NonNull MutableOffsetMap<K, V> toModifiableMap();
 
     abstract void setFields(List<K> keys, V[] values) throws IOException;
 
     /**
-     * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This
-     * is actually not completely true, as this method returns an
-     * {@link ImmutableMap} for empty and singleton inputs, as those are more
-     * memory-efficient. This method also recognizes {@link ImmutableOffsetMap}
-     * on input, and returns it back without doing anything else. It also
-     * recognizes {@link MutableOffsetMap} (as returned by
-     * {@link #toModifiableMap()}) and makes an efficient copy of its contents.
-     * All other maps are converted to an {@link ImmutableOffsetMap} with the
-     * same iteration order as input.
+     * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
+     * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
+     * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
+     * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
+     * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
+     * {@link ImmutableOffsetMap} with the same iteration order as input.
      *
-     * @param map
-     *            Input map, may not be null.
+     * @param map Input map, may not be null.
      * @return An isolated, immutable copy of the input map
+     * @throws NullPointerException if {@code map} or any of its elements is null.
      */
-    @Nonnull public static <K, V> Map<K, V> orderedCopyOf(@Nonnull final Map<K, V> map) {
-        // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
-        if (map instanceof ImmutableOffsetMap || map instanceof SharedSingletonMap) {
-            return map;
-        }
-
-        // Familiar and efficient to copy
-        if (map instanceof MutableOffsetMap) {
-            return ((MutableOffsetMap<K, V>) map).toUnmodifiableMap();
+    public static <K, V> @NonNull Map<K, V> orderedCopyOf(final @NonNull Map<K, V> map) {
+        final Map<K, V> common = commonCopy(map);
+        if (common != null) {
+            return common;
         }
 
         final int size = map.size();
-        if (size == 0) {
-            // Shares a single object
-            return ImmutableMap.of();
-        }
         if (size == 1) {
             // Efficient single-entry implementation
             final Entry<K, V> e = map.entrySet().iterator().next();
             return SharedSingletonMap.orderedOf(e.getKey(), e.getValue());
         }
 
-        final Map<K, Integer> offsets = OffsetMapCache.orderedOffsets(map.keySet());
+        final ImmutableMap<K, Integer> offsets = OffsetMapCache.orderedOffsets(map.keySet());
         @SuppressWarnings("unchecked")
         final V[] array = (V[]) new Object[offsets.size()];
         for (Entry<K, V> e : map.entrySet()) {
@@ -152,43 +145,30 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
     }
 
     /**
-     * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This
-     * is actually not completely true, as this method returns an
-     * {@link ImmutableMap} for empty and singleton inputs, as those are more
-     * memory-efficient. This method also recognizes {@link ImmutableOffsetMap}
-     * on input, and returns it back without doing anything else. It also
-     * recognizes {@link MutableOffsetMap} (as returned by
-     * {@link #toModifiableMap()}) and makes an efficient copy of its contents.
-     * All other maps are converted to an {@link ImmutableOffsetMap}. Iterator
-     * order is not guaranteed to be retained.
+     * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
+     * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
+     * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
+     * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
+     * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
+     * {@link ImmutableOffsetMap}. Iterator order is not guaranteed to be retained.
      *
-     * @param map
-     *            Input map, may not be null.
+     * @param map Input map, may not be null.
      * @return An isolated, immutable copy of the input map
+     * @throws NullPointerException if {@code map} or any of its elements is null.
      */
-    @Nonnull public static <K, V> Map<K, V> unorderedCopyOf(@Nonnull final Map<K, V> map) {
-        // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
-        if (map instanceof ImmutableOffsetMap || map instanceof SharedSingletonMap) {
-            return map;
+    public static <K, V> @NonNull Map<K, V> unorderedCopyOf(final @NonNull Map<K, V> map) {
+        final Map<K, V> common = commonCopy(map);
+        if (common != null) {
+            return common;
         }
 
-        // Familiar and efficient to copy
-        if (map instanceof MutableOffsetMap) {
-            return ((MutableOffsetMap<K, V>) map).toUnmodifiableMap();
-        }
-
-        final int size = map.size();
-        if (size == 0) {
-            // Shares a single object
-            return ImmutableMap.of();
-        }
-        if (size == 1) {
+        if (map.size() == 1) {
             // Efficient single-entry implementation
             final Entry<K, V> e = map.entrySet().iterator().next();
             return SharedSingletonMap.unorderedOf(e.getKey(), e.getValue());
         }
 
-        final Map<K, Integer> offsets = OffsetMapCache.unorderedOffsets(map.keySet());
+        final ImmutableMap<K, Integer> offsets = OffsetMapCache.unorderedOffsets(map.keySet());
         @SuppressWarnings("unchecked")
         final V[] array = (V[]) new Object[offsets.size()];
         for (Entry<K, V> e : map.entrySet()) {
@@ -198,6 +178,25 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
         return new Unordered<>(offsets, array);
     }
 
+    private static <K, V> @Nullable Map<K, V> commonCopy(final @NonNull Map<K, V> map) {
+        // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
+        if (map instanceof ImmutableOffsetMap || map instanceof SharedSingletonMap) {
+            return map;
+        }
+
+        // Familiar and efficient to copy
+        if (map instanceof MutableOffsetMap) {
+            return ((MutableOffsetMap<K, V>) map).toUnmodifiableMap();
+        }
+
+        if (map.isEmpty()) {
+            // Shares a single object
+            return ImmutableMap.of();
+        }
+
+        return null;
+    }
+
     @Override
     public final int size() {
         return offsets.size();
@@ -283,8 +282,8 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
 
     @Override
     public final V get(final Object key) {
-        final Integer offset = offsets.get(key);
-        return offset == null ? null : objects[offset];
+        Integer offset;
+        return (offset = offsets.get(key)) == null ? null : objects[offset];
     }
 
     @Override
@@ -299,7 +298,7 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
 
     @Override
     @SuppressWarnings("checkstyle:parameterName")
-    public final void putAll(@Nonnull final Map<? extends K, ? extends V> m) {
+    public final void putAll(final Map<? extends K, ? extends V> m) {
         throw new UnsupportedOperationException();
     }
 
@@ -313,15 +312,13 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
         return offsets.keySet();
     }
 
-    @Nonnull
     @Override
-    public final Collection<V> values() {
+    public final @NonNull Collection<V> values() {
         return new ConstantArrayCollection<>(objects);
     }
 
-    @Nonnull
     @Override
-    public final Set<Entry<K, V>> entrySet() {
+    public final @NonNull Set<Entry<K, V>> entrySet() {
         return new EntrySet();
     }
 
@@ -331,9 +328,7 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
         final Iterator<K> it = offsets.keySet().iterator();
         int offset = 0;
         while (it.hasNext()) {
-            sb.append(it.next());
-            sb.append('=');
-            sb.append(objects[offset++]);
+            sb.append(it.next()).append('=').append(objects[offset++]);
 
             if (it.hasNext()) {
                 sb.append(", ");
@@ -343,21 +338,19 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
         return sb.append('}').toString();
     }
 
-    final Map<K, Integer> offsets() {
+    final @NonNull ImmutableMap<K, Integer> offsets() {
         return offsets;
     }
 
-    final V[] objects() {
+    final @NonNull V[] objects() {
         return objects;
     }
 
     private final class EntrySet extends AbstractSet<Entry<K, V>> {
-        @Nonnull
         @Override
-        public Iterator<Entry<K, V>> iterator() {
+        public @NonNull Iterator<Entry<K, V>> iterator() {
             final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
-
-            return new UnmodifiableIterator<Entry<K, V>>() {
+            return new UnmodifiableIterator<>() {
                 @Override
                 public boolean hasNext() {
                     return it.hasNext();
@@ -388,7 +381,7 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
     private static final Field OFFSETS_FIELD = fieldFor("offsets");
     private static final Field ARRAY_FIELD = fieldFor("objects");
 
-    private static Field fieldFor(final String name) {
+    private static @NonNull Field fieldFor(final @NonNull String name) {
         final Field f;
         try {
             f = ImmutableOffsetMap.class.getDeclaredField(name);
@@ -400,8 +393,10 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
         return f;
     }
 
-    private static void setField(final ImmutableOffsetMap<?, ?> map, final Field field, final Object value)
-            throws IOException {
+    @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
+            justification = "https://github.com/spotbugs/spotbugs/issues/811")
+    private static void setField(final @NonNull ImmutableOffsetMap<?, ?> map, final @NonNull Field field,
+            final Object value) throws IOException {
         try {
             field.set(map, value);
         } catch (IllegalArgumentException | IllegalAccessException e) {
@@ -410,7 +405,7 @@ public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K
     }
 
     @SuppressWarnings("unchecked")
-    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
+    private void readObject(final @NonNull ObjectInputStream in) throws IOException, ClassNotFoundException {
         final int s = in.readInt();
 
         final List<K> keys = new ArrayList<>(s);