Ответ 1
Да, посмотрите Apache Commons Pair
.
Используйте экономно, , если вообще; left
и right
на самом деле ничего не сообщают о содержании или отношении между элементами.
(Класс Pair
был умышленно оставлен вне стандартного Java API.)
Есть ли проверенная реализация класса Java Pair?
Я имею в виду легкодоступную, широко распространенную и проверенную, возможно, часть более обширной библиотеки, такой как Apache Commons или Guava.
Да, посмотрите Apache Commons Pair
.
Используйте экономно, , если вообще; left
и right
на самом деле ничего не сообщают о содержании или отношении между элементами.
(Класс Pair
был умышленно оставлен вне стандартного Java API.)
Map.Entry
Что насчет интерфейса java.util.Map.Entry
?
Две конкретные реализации в комплекте с Java 6 и более поздними версиями:
Я использовал AbstractMap.SimpleEntry и AbstractMap.SimpleImmutableEntry, когда нужно хранить пары (например, размер и объект сбор).
Этот фрагмент из моего производственного кода:
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));
}
Код выглядит сложным, но вместо Map.Entry вы ограничиваетесь массивом объекта (размером 2) и теряете проверки типа...
Вот реализация из Android SDK:
/**
* 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 имеет его как javafx.util.Pair
.
http://docs.oracle.com/javafx/2/api/javafx/util/Pair.html
Если вы включите jfxrt.jar в Java SDK, вы можете его использовать.
Мое решение было:
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()+"]";
}
}
Очень просто, со всеми преимуществами обернутого класса AbstractMap.SimpleImmutableEntry.