2011-09-06 17 views
34

È disponibile un'implementazione della classe Pair Java dimostrata?Coppia Java <T,N> implementazione classe

Intendo prontamente disponibile, ampiamente accettato e testato, forse parte di una libreria più ampia come Apache Commons o Guava.

+5

possibile duplicato di [Qual è l'equivalente della coppia C++ in Java?] (Http://stackoverflow.com/questions/156275/questo-è-il-equivalente-della-c-pairl-r -in-java) – Thilo

+0

Ecco l'elenco delle classi di coppia in diversi framework: http://javasearch.buggybread.com/home.php?keyword=%3DPair –

risposta

33

Sì, dai un'occhiata a Apache Commons Pair.

Utilizzare con parsimonia, se non del tutto; left e right non trasmettono nulla sul contenuto o sulla relazione tra gli elementi.

(La classe Pair è stato volutamente lasciato fuori delle API standard di Java.)

+0

+1. infine ... Commons Lang 2 non ce l'ha (senza i generici è meno interessante in ogni caso) – Thilo

+1

Sembra che lo abbiano diviso in MutablePair e ImmutablePair dalla beta (a cui hai collegato), però: http: //commons.apache. org/lang/api/org/apache/commons/lang3/tuple/Pair.html – Thilo

+2

"' left' e 'right' non trasmettono nulla sul contenuto" Pair implements Map.Entrata, in modo che tu possa almeno chiamarli anche 'chiave' e' valore'. – Thilo

6

Ho usato AbstractMap.SimpleEntry e AbstractMap.SimpleImmutableEntry quando il bisogno di memorizzare coppie (come la dimensione e la raccolta di oggetti).

Questo pezzo dal mio codice di produzione:

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)); 
} 

codice sembra complicato ma invece di Map.Entry si limitato alla gamma di oggetti (con dimensioni 2) e perdere controlli di tipo ...

5

Ecco un'implementazione del SDK di 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

La mia soluzione era:

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()+"]"; 
    } 

} 

Molto semplice, con tutti i vantaggi della classe AbstractMap.SimpleImmutableEntry avvolto.

+0

Grazie per questa semplice gemma !! Mi ha aiutato molto – user238607

Problemi correlati