I have an assignment where the goal is to create a HashTable implementation with generic keys and values. To handle collisions, we were told to use separate chaining. So, I tried doing this:
public class HashTable<K, V> implements Table<K, V> {
private Node[] generics;
public class Node {
V value;
Node next;
public Node(V val) {
value = val;
}
}
public HashTable(int size) {
generics = (Node[]) new Object[size];
}
}
For the separate chaining, I wanted to use a linked list implementation (what else), which is why I need generics
to hold Node
's, not just V
's. The reason I cannot just write generics = new Node[size];
is that the Node class contains a generic, and generic array creation is not allowed. For this assignment, this workaround, which produces an "unchecked cast" warning, is acceptable.
Then, in the driver, it tries Table<String, String> ht = new HashTable<String, String>(5);
and gets a ClassCastException. There was no ClassCastException when generics
was a V[]
, for context.
So, my question is: How do I create a custom class array, where the custom class contains generics (without changing the driver)?
Try below solution
public class HashTable<K, V> {
private Node<V>[] generics;
static class Node<V> {
V value;
Node next;
public Node(V val) {
value = val;
}
}
private HashTable(int size) {
generics = (Node<V>[]) new Node[size];
}
}
generics = (Node[]) new Node[size]; this line will give you unchecked cast warning for this code impl check HashMap source code
And if you want to remove unchecked cast warning than you wildcard in generic type reference
public class HashTable<K, V> {
private Node<?>[] generics;
static class Node<V> {
V value;
Node next;
public Node(V val) {
value = val;
}
}
public HashTable(int size) {
generics = new Node<?>[size];
}
}
it will not give you any "unchecked cast" warning. for this you can HashTable source code