¿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.
¿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.
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.)
+1. finalmente ... Commons Lang 2 no tenía eso (sin genéricos es menos interesante de todos modos) – Thilo
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
"' 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
Map.Entry
¿Qué hay de java.util.Map.Entry
interfaz?
Dos aplicación concreta incluido con Java 6 y posteriores:
Desafortunadamente, ya que: 1.6 – yannisf
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 ...
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);
}
}
JavaFX tiene como javafx.util.Pair
.
http://docs.oracle.com/javafx/2/api/javafx/util/Pair.html
Si incluye jfxrt.jar en Java SDK se puede usar.
javafx es un no si eres usando openJDK – Allenaz
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.
¡Gracias por esta simple joya! Me ayudo mucho. – user238607
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
Aquí está la lista de clases de pares en diferentes marcos - http://javasearch.buggybread.com/home.php?keyword=%3DPair –