В Java нет класса с именем Pair
; но есть интерфейс Map.Entry<K,V>
, и есть две его публичные реализации: AbstractMap.SimpleEntry
и AbstractMap.SimpleImmutableEntry
.
Если вам неприятно использовать вложенные классы непосредственно в коде, вы всегда можете создать класс Pair:
public class Pair<Type1, Type2> extends AbstractMap.SimpleEntry<Type1, Type2> {
public Pair(Type1 t1, Type2 t2) {
super(t1, t2);
}
}
Или вы можете написать свое собственное так:
public final class Pair<Type1, Type2> {
public final Type1 first;
public final Type2 second;
public Pair(Type1 first, Type2 second) {
this.first = first;
this.second = second;
}
/**
* Factory method to ease the pain of generics.
*/
public static <T1, T2> Pair of(T1 first, T2 second) {
return new Pair<T1, T2>(first, second);
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Pair other = (Pair) obj; // no generics needed here
if (this.first != other.first &&
(this.first == null || !this.first.equals(other.first)))
return false;
if (this.second != other.second &&
(this.second == null || !this.second.equals(other.second)))
return false;
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 37 * hash + (this.first != null ? this.first.hashCode() : 0);
hash = 37 * hash + (this.second != null ? this.second.hashCode() : 0);
return hash;
}
}