C++对<L,R>的等价物是什么?在 Java 中?

2022-01-19 00:00:00 tuples java std-pair

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

Is there a good reason why there is no Pair<L,R> in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own.

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

It seems that 1.6 is providing something similar (AbstractMap.SimpleEntry<K,V>), but this looks quite convoluted.

推荐答案

comp.lang.java.help 上的一个线程,Hunter Gratzner 给出了一些反对 Java 中存在 Pair 构造的论据.主要论点是类 Pair 没有传达关于两个值之间关系的任何语义(你怎么知道第一"和第二"是什么意思?).

In a thread on comp.lang.java.help, Hunter Gratzner gives some arguments against the presence of a Pair construct in Java. The main argument is that a class Pair doesn't convey any semantics about the relationship between the two values (how do you know what "first" and "second" mean ?).

更好的做法是编写一个非常简单的类,就像 Mike 提议的那样,为您将使用 Pair 类创建的每个应用程序.Map.Entry 是一对在其名称中包含其含义的示例.

A better practice is to write a very simple class, like the one Mike proposed, for each application you would have made of the Pair class. Map.Entry is an example of a pair that carry its meaning in its name.

总结一下,我认为最好有一个类Position(x,y),一个类Range(begin,end)和一个类Entry(key,value) 而不是一个通用的 Pair(first,second),它不会告诉我它应该做什么.

To sum up, in my opinion it is better to have a class Position(x,y), a class Range(begin,end) and a class Entry(key,value) rather than a generic Pair(first,second) that doesn't tell me anything about what it's supposed to do.

相关文章