import java.util.Objects;
import java.util.HashMap;
import java.util.Map;
class CustomKey {
private String id;
private int age;
public CustomKey(String id, int age) {
this.id = id;
this.age = age;
}
// Override equals() to compare objects logically
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomKey that = (CustomKey) o;
return age == that.age && Objects.equals(id, that.id);
}
// Override hashCode() to generate consistent hash codes
@Override
public int hashCode() {
return Objects.hash(id, age);
}
@Override
public String toString() {
return "CustomKey{" + "id='" + id + '\'' + ", age=" + age + '}';
}
}
public class Main {
public static void main(String[] args) {
Map<CustomKey, String> map = new HashMap<>();
CustomKey key1 = new CustomKey("A", 1);
CustomKey key2 = new CustomKey("B", 2);
map.put(key1, "Value for Key1");
map.put(key2, "Value for Key2");
// Print all entries in the map
for (Map.Entry<CustomKey, String> entry : map.entrySet()) {
CustomKey key = entry.getKey();
String value = entry.getValue();
System.out.println("Key: " + key + " => Value: " + value);
}
}
}
/*
run:
Key: CustomKey{id='A', age=1} => Value: Value for Key1
Key: CustomKey{id='B', age=2} => Value: Value for Key2
*/