Java中没有Pair<L,R>,有什么好理由吗?与这个c++构造等价的是什么?我宁愿避免重新实现我自己的。

似乎1.6提供了类似的东西(AbstractMap.SimpleEntry<K,V>),但这看起来相当复杂。


当前回答

如果有人想要一个简单易用的版本,我在https://github.com/lfac-pt/Java-Pair上提供了我的版本。此外,非常欢迎改进!

其他回答

好消息JavaFX有一个键值Pair。

只需添加JavaFX作为依赖项并导入JavaFX .util。对,并像在c++中那样简单地使用。

Pair <Key, Value> 

e.g.

Pair <Integer, Integer> pr = new Pair<Integer, Integer>()

pr.get(key);// will return corresponding value

实现Pair with的另一种方法。

Public immutable fields, i.e. simple data structure. Comparable. Simple hash and equals. Simple factory so you don't have to provide the types. e.g. Pair.of("hello", 1); public class Pair<FIRST, SECOND> implements Comparable<Pair<FIRST, SECOND>> { public final FIRST first; public final SECOND second; private Pair(FIRST first, SECOND second) { this.first = first; this.second = second; } public static <FIRST, SECOND> Pair<FIRST, SECOND> of(FIRST first, SECOND second) { return new Pair<FIRST, SECOND>(first, second); } @Override public int compareTo(Pair<FIRST, SECOND> o) { int cmp = compare(first, o.first); return cmp == 0 ? compare(second, o.second) : cmp; } // todo move this to a helper class. private static int compare(Object o1, Object o2) { return o1 == null ? o2 == null ? 0 : -1 : o2 == null ? +1 : ((Comparable) o1).compareTo(o2); } @Override public int hashCode() { return 31 * hashcode(first) + hashcode(second); } // todo move this to a helper class. private static int hashcode(Object o) { return o == null ? 0 : o.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) return false; if (this == obj) return true; return equal(first, ((Pair) obj).first) && equal(second, ((Pair) obj).second); } // todo move this to a helper class. private boolean equal(Object o1, Object o2) { return o1 == null ? o2 == null : (o1 == o2 || o1.equals(o2)); } @Override public String toString() { return "(" + first + ", " + second + ')'; } }

为了方便起见,以下是一些具有多级元组的库:

JavaTuples。它只有1-10度的元组。 JavaSlang。0-8度的元组和许多其他功能性的东西。 jOOλ。0-16度的元组和其他一些功能性的好东西。(免责声明,我在维修公司工作) Functional Java。0-8度的元组和许多其他功能性的东西。

已经提到的其他库至少包含Pair元组。

具体来说,在函数式编程的上下文中,它使用了大量的结构类型,而不是名义类型(正如公认答案中提倡的那样),这些库及其元组非常方便。

您可以使用谷歌的AutoValue库- https://github.com/google/auto/tree/master/value。

您创建一个非常小的抽象类,并使用@AutoValue注释它,注释处理器为您生成一个具有值语义的具体类。

这是Java。您必须使用描述性的类名和字段名创建自己定制的Pair类,不要介意通过编写hashCode()/equals()或一次又一次地实现Comparable来重新发明轮子。