'Creating a hash table with tuple as key
I am trying to implement a HashTable that uses tuples of integers as keys. What i have done so far:
import java.util.*;
public class Hash_Table_Demo {
public static void main(String[] args)
{
Hashtable<Integer, String> marks =
new Hashtable<Integer, String>();
marks.put(33,"test");
System.out.println(marks.get(33));
}
}
So far i have achieved this only for integers and not for pairs. How could this be done?
Solution 1:[1]
Updated version
To avoid the dependency to JavaFX we can create a simple generic class for the tuple
class Tuple<Value> {
Value first;
Value second;
Tuple(Value first, Value second) {
this.first = first;
this.second = second;
}
}
and also avoid using Hashtable
and replace it with for instance. HashMap
Map<Tuple<Integer>, String> map = new HashMap();
map.put(new Tuple(1,2), "Hello");
map.put(new Tuple(3,3), "World");
Old version
Using the existing Pair class you can define your hash table like
Map<Pair<Integer, Integer>, String> marks = new Hashtable<>();
And then create a new Pair instance as key
marks.put(new Pair(1,33),"test");
System.out.println(marks.get(new Pair(1,33)));
Solution 2:[2]
So long story short, unlike c# that has value tuples since version 7 and you can use
(string name, int age) info = GetStudentInfo("100-000-1000");
As you can see, it is a tuple, but elements have strong types and names. You can compare them and most of it works nicely. Python is scripting language and has had this support for ages. In java, if you create a class you need to override its hashcode, tostring, ... and if you want to have multi threading guarantees it is just hard.
Thankfully Google engineers have stumbled upon this multiple times and have solved this issue as best as it is possible, for more info check out Guava horrible ideas: https://github.com/google/guava/wiki/IdeaGraveyard
The solution is to use AutoValue that generates immutable value classes https://github.com/google/auto/tree/master/value
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class Pair {
public static Pair of(int first, int second) {
return new AutoValue_Pair(first, second);
}
public abstract int first();
public abstract int second();
}
To use it you could just type
Hashtable<Pair, String> marks = new Hashtable<Pair, String>();
marks.put(Pair.of(1, 2), "test");
The real strengths start to shine when you scale your problem or when you use it with google guava with it. For example:
Map<Pair, String> map = Maps.newLinkedHashMap();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |