I want to implement the following idea in Java: If I map one object of a class having 2 members to a Boolean value, and create another object of the same class with same 2 member values, the second object should map to the same Boolean value as the first one.
Here is the code in C++ that hopefully explains what I'm trying to do:
#include <iostream>
#include <map>
using namespace std;
class A{
int x;
int y;
public:
A(int a, int b){
x = a;
y = b;
}
bool operator < (const A &another) const{
return x < another.x || y < another.y;
}
};
int main() {
A a(1,2),b(1,2);
map <A,bool> exists;
exists[a]=true;
if(exists[b]){
cout << "(1,2) exists" << endl;
}
else{
cout << "(1,2) does not exist" << endl;
}
return 0;
}
Output:
(1,2) exists
Here a and b are not the same object but they have the same member values. So they map to the same Boolean value.
I have tried using HashMap in Java to implement this without success:
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
A a = new A(1,2);
A b = new A(1,2);
Map <A,Boolean> exists = new HashMap<A,Boolean>();
exists.put(a,true);
if(exists.containsKey(b)){
System.out.println("(1,2) exists");
}
else{
System.out.println("(1,2) does not exist");
}
}
}
class A{
private int x;
private int y;
public A(int a, int b){
x = a;
y = b;
}
}
Output:
(1,2) does not exist
How should I implement this in Java?