This question was asked to me in an interview. I think the only way to get best solution is SOF. So the question was \"How would you implement a custom HashMap in java(A
adding just one more approach - how about if we use set instead of hashMap in this way
Create a custom class called pair -
public class Pair {
private String key;
private Object Value;
public Pair(String key, Object value) {
this.key = key;
Value = value;
}
public String getKey() {
return key;
}
public Object getValue() {
return Value;
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (key != other.getKey())
return false;
return true;
}
}
and then you can directly use java Set as Hashmap
public static void main(String[] args) {
Set<Pair> set = new HashSet<Pair>();
set.add(new Pair("key1", "val1"));
set.add(new Pair("key2", "val2"));
set.add(new Pair("key1", "val3"));
// you can advanced for loop for looping over set
for (Pair pair : set) {
}
// with java 8 - you can also use streams over it
// set.stream().filter
// set.stream().anyMatch
// and some more methods can be directly used
}
With Java-8 Stream API - it will enable this to make some more operations easy and fast.
Just adding this as one more possible approach for custom hashmap -