Reputation: 760
Are they added benefits to writing my own hash map data structure instead of using a pre written class like hashmap in java.
Background. Im writing a spring application that requires data structure that can map a single key to map to two values.
the current benefits i can think of now will be: - can include more methods such as swap (swap value 1 with 2) - more control over hashing functions - more control in general
was wondering: - if they are any draw backs in terms of performance or complexity - or if it makes any sense at all to write my own data structure
Thanks for taking the time to read.
EDIT: If it helps helps. i only need fast access speed (methods like get and contains) for methods that "put", time taken can be a little longer Any suggestion on what i should do?
Upvotes: 2
Views: 206
Reputation: 424983
Keep it simple: Use HashMap
whose value type is a simple class to hold two values, eg (for simplicity, I have assumed key and both values are String):
class Pair {
private String a;
private String b;
public Pair(String a, String b) {
this.a = a;
this.b = b;
}
public String getA() {
return a;
}
public String getB() {
return b;
}
public void swap() {
// Note: Not threadsafe
String tmp = a;
a = b;
b = tmp;
}
public boolean equals(Object o) {
return o instanceof Pair
&& Objects.equals(a, ((Pair)o).a
&& Objects.equals(b, ((Pair)o).b;
}
public int hashCode() {
return Objects.hash(a, b);
}
}
Map<String, Pair> map = new HashMap<>();
Upvotes: 2
Reputation: 3151
You risk missing out on a very well-vetted, proven and durable framework by not using the java.util
package. No offense, but it's unlikely you're going to come up with a better design and implementation, especially one as bug-free and optimized as part of Java's core API. Rather, use what exists and either write your own small methods, extend the existing HashMap, or find another open-source variant (e.g. maybe from Apache FastHashMap) to get the additional required functionality.
Upvotes: 1