Il n'existe aucune classe appelée Pair
en Java; mais il y a l'interface Map.Entry<K,V>
, et il y a deux implémentations publiques de celui-ci: AbstractMap.SimpleEntry
et AbstractMap.SimpleImmutableEntry
.
Si vous trouvez laid utiliser les classes imbriquées directement dans votre code, vous pouvez toujours créer une classe Pair:
public class Pair<Type1, Type2> extends AbstractMap.SimpleEntry<Type1, Type2> {
public Pair(Type1 t1, Type2 t2) {
super(t1, t2);
}
}
Ou vous pouvez écrire votre propre comme ceci:
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;
}
}
Que voulez-vous dire par "représenter"? Voulez-vous simplement simplifier le code? Cherchez-vous quelque chose de similaire à un typedef en C++? –
Voir aussi http: // stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java –