Elem.java

  1. package no.motif.single;

  2. import java.io.Serializable;
  3. import java.util.Objects;

  4. import no.motif.f.Fn;

  5. /**
  6.  * A simple container for a value coupled with an index.
  7.  *
  8.  * @param <T> The type of the containing value.
  9.  */
  10. public final class Elem<T> implements Serializable {

  11.     public final int index;
  12.     public final T value;

  13.     public static <T> Elem<T> of(int index, T value) {
  14.         return new Elem<T>(index, value);
  15.     }

  16.     private Elem(int index, T value) {
  17.         this.index = index;
  18.         this.value = value;
  19.     }

  20.     @Override
  21.     public boolean equals(Object o) {
  22.         if (o instanceof Elem) {
  23.             Elem<?> another = (Elem<?>) o;
  24.             return this.index == another.index && Objects.equals(this.value, another.value);
  25.         }
  26.         return false;
  27.     }

  28.     @Override
  29.     public int hashCode() {
  30.         return Objects.hash(index, value);
  31.     }

  32.     @Override
  33.     public String toString() {
  34.         return "[" + index + ": " + value + "]";
  35.     }

  36.     public static <T> Fn<T, Elem<T>> withIndex(final int index) { return new Fn<T, Elem<T>>() {
  37.         @Override public Elem<T> $(T value) { return new Elem<T>(index, value); }}; }
  38. }