问题描述
Java 中没有 Pair
是否有充分的理由?这个 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
),但这看起来很复杂.
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 ?).
更好的做法是为每个由 Pair
类组成的应用程序编写一个非常简单的类,就像 Mike 建议的那样.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.
这篇关于C++ Pair L,R 的等价物是什么?在爪哇?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!