Question is similar to this Why do we have to use an intermediary variable for @SuppressWarnings("unchecked")?, but I couldn't glean a solution from that one.
As an exercise, I'm building a hash-table construct from scratch. So I wrote a class LinkedListDemo auxiliary to HashTableDemo; the LinkedListDemo class tests absolutely fine. Particularly, the following subroutine in causes no ClassCastException errors at run-time:
public LinkedListDemo<S, T> reverse() {
if (count == 0)
return null;
@SuppressWarnings("unchecked")
S[] keys = (S[]) new Object[count];
@SuppressWarnings("unchecked")
T[] vals = (T[]) new Object[count];
ListNode<S, T> runner = head;
for (int k = 0; k < count; k++) {
keys[k] = runner.pair.getKey();
vals[k] = runner.pair.getValue();
runner = runner.next;
}
ArrayUtils.reverse(keys);
ArrayUtils.reverse(vals);
return new LinkedListDemo<S, T>(keys, vals);
}
Whereas the following, in my HashTable class does:
public class HashTableDemo<S, T> {
private LinkedListDemo<S, T>[] table = (LinkedListDemo<S, T>[]) new Object[10];
// more code...
}
Does anyone know how Java's HashMap class circumvents this issue, and/or how I can? I tried creating an intermediate variable within a constructor as suggested in the above link - but it didn't work.