【发布时间】:2013-03-26 09:26:01
【问题描述】:
如何在Java中实现类对,就像在C++中一样,在C++中使用?
【问题讨论】:
-
在大多数情况下,最好 a) 使用描述两个字段的类,而不仅仅是“left”和“right”,或者 b) 首先避免需要这样的类.
如何在Java中实现类对,就像在C++中一样,在C++中使用?
【问题讨论】:
当我这样做时,我做了一些类似于标准库中的Map.Entry<K, V> 接口的事情。您可能应该覆盖 Object.equals(Object) 和 Object.hashCode() 以便键和值在逻辑上彼此相等的两个对在逻辑上相等并且散列相同 - 请参阅 Bloch 的 Effective Java 的第 9 项以获取有关如何做好实现的一些指针.
这就是我所做的:
@Override
public String toString() {
//same convention as AbstractMap.SimpleEntry
return key + "=" + value;
}
@Override
public boolean equals(Object o) {
if(o == this) return true;
if(!(o instanceof Pair)) return false;
Object otherKey = ((Pair<?, ?>)o).getKey();
Object otherValue = ((Pair<?, ?>)o).getValue();
return (key == null ? otherKey == null : key.equals(otherKey))
&& (value == null ? otherValue == null
: value.equals(otherValue));
}
@Override
public int hashCode() {
return 17 + 55555 * (key == null ? 72 : key.hashCode())
+ 232323 * (value == null ? 73 : value.hashCode());
}
【讨论】:
class Pair<F,S> {
private F first;
private S second;
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
public F getFirst() { return first }
public S getSecond() { return second }
}
【讨论】:
你只需要包含正确的标题
#include <utility>
#include <string>
using std::string;
using std::makepair;
using std::pair;
void foo()
{
string hello("Hello");
float value(42);
auto p = makepair(hello, value); // or: pair<string, float> = ...
}
【讨论】: