2011-09-06 27 views
34

¿Existe una implementación probada de la clase Java Pair?Java Pair <T,N> implementación de clase

Me refiero a disponible, ampliamente aceptado y probado, tal vez parte de una biblioteca más extensa como Apache Commons o Guava.

+5

posible duplicado de [¿Cuál es el equivalente del par de C++ en Java?] (Http://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r -in-java) – Thilo

+0

Aquí está la lista de clases de pares en diferentes marcos - http://javasearch.buggybread.com/home.php?keyword=%3DPair –

Respuesta

33

Sí, eche un vistazo a Apache Commons Pair.

Usar con moderación, en todo caso; left y right realmente no transmiten nada sobre el contenido o la relación entre los elementos.

(La clase Pair fue dejado deliberadamente fuera de la API estándar de Java.)

+0

+1. finalmente ... Commons Lang 2 no tenía eso (sin genéricos es menos interesante de todos modos) – Thilo

+1

Parece que lo dividen en MutablePair y en ImmutablePair desde la versión beta (a la que vinculó), aunque: http: //commons.apache. org/lang/api/org/apache/commons/lang3/tuple/Pair.html – Thilo

+2

"' left' y 'right' realmente no transmiten nada sobre el contenido" Pair implementa Map.Entrada, para que al menos también pueda llamarlos 'clave' y' valor'. – Thilo

6

que utilizan AbstractMap.SimpleEntry y cuando AbstractMap.SimpleImmutableEntry necesidad de almacenar pares (como el tamaño y la colección de objetos).

Esta pieza de mi código de producción:

public Map<L1Risk, Map.Entry<int[], Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>>>> 
     getEventTable(RiskClassifier classifier) { 
    Map<L1Risk, Map.Entry<int[], Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>>>> l1s = new HashMap<>(); 
    Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>> l2s = new HashMap<>(); 
    Map<L3Risk, List<Event>> l3s = new HashMap<>(); 
    List<Event> events = new ArrayList<>(); 
    ... 
    map.put(l3s, events); 
    map.put(l2s, new AbstractMap.SimpleImmutableEntry<>(l3Size, l3s)); 
    map.put(l1s, new AbstractMap.SimpleImmutableEntry<>(l2Size, l2s)); 
} 

Código ve muy complicado pero en lugar de Map.Entry se limita a variedad de objetos (con un tamaño de 2) y perder los controles de tipo ...

5

Aquí es una implementación del SDK de Android:

/** 
* Container to ease passing around a tuple of two objects. This object provides a sensible 
* implementation of equals(), returning true if equals() is true on each of the contained 
* objects. 
*/ 
public class Pair<F, S> { 
    public final F first; 
    public final S second; 

    /** 
    * Constructor for a Pair. 
    * 
    * @param first the first object in the Pair 
    * @param second the second object in the pair 
    */ 
    public Pair(F first, S second) { 
     this.first = first; 
     this.second = second; 
    } 

    /** 
    * Checks the two objects for equality by delegating to their respective 
    * {@link Object#equals(Object)} methods. 
    * 
    * @param o the {@link Pair} to which this one is to be checked for equality 
    * @return true if the underlying objects of the Pair are both considered 
    *   equal 
    */ 
    @Override 
    public boolean equals(Object o) { 
     if (!(o instanceof Pair)) { 
      return false; 
     } 
     Pair<?, ?> p = (Pair<?, ?>) o; 
     return Objects.equal(p.first, first) && Objects.equal(p.second, second); 
    } 

    /** 
    * Compute a hash code using the hash codes of the underlying objects 
    * 
    * @return a hashcode of the Pair 
    */ 
    @Override 
    public int hashCode() { 
     return (first == null ? 0 : first.hashCode())^(second == null ? 0 : second.hashCode()); 
    } 

    /** 
    * Convenience method for creating an appropriately typed pair. 
    * @param a the first object in the Pair 
    * @param b the second object in the pair 
    * @return a Pair that is templatized with the types of a and b 
    */ 
    public static <A, B> Pair <A, B> create(A a, B b) { 
     return new Pair<A, B>(a, b); 
    } 
} 
2

Mi solución fue:

public class Pair<F, S> extends java.util.AbstractMap.SimpleImmutableEntry<F, S> { 

    public Pair(F f, S s) { 
     super(f, s); 
    } 

    public F getFirst() { 
     return getKey(); 
    } 

    public S getSecond() { 
     return getValue(); 
    } 

    public String toString() { 
     return "["+getKey()+","+getValue()+"]"; 
    } 

} 

muy sencilla, con todos los beneficios de la clase AbstractMap.SimpleImmutableEntry envueltos.

+0

¡Gracias por esta simple joya! Me ayudo mucho. – user238607

Cuestiones relacionadas