How to realize class pair in Java like in C++, for using like in C++?
Asked
Active
Viewed 2,351 times
-4
-
see this http://stackoverflow.com/questions/5303539/didnt-java-once-have-a-pair-class – Ankit Apr 04 '13 at 10:45
-
In most cases, it's a better idea to either a) use a class which describes the two fields, not just "left" and "right" or b) avoid needing such a class in the first place. – Peter Lawrey Apr 04 '13 at 11:26
3 Answers
0
When I did it I did something similar to the Map.Entry<K, V>
interface from the standard library. You should probably override Object.equals(Object)
and Object.hashCode()
so that two pairs where the key and value are logically equal to each other are logically equal and hash the same - see item 9 of Bloch's Effective Java for some pointers on how to do good implementations.
Here's what I did:
@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());
}

Injektilo
- 581
- 3
- 14
-1
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 }
}

maba
- 47,113
- 10
- 108
- 118
-
The C++ pair template allows a different type for the first and second elements – Injektilo Apr 04 '13 at 10:51
-
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Mar 11 '17 at 19:44
-1
You just have to include the right header
#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> = ...
}

ogni42
- 1,232
- 7
- 11