The question is similar to this. Why should we use an intermediate variable for @SuppressWarnings ("unchecked"?)? but I could not get a solution from this.
As an exercise, I build a hash table design from scratch. So I wrote an additional LinkedListDemo class for HashTableDemo; LinkedListDemo tests are great. In particular, the following routine does not throw ClassCastException errors at runtime:
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); }
While in my HashTable class the following:
public class HashTableDemo<S, T> { private LinkedListDemo<S, T>[] table = (LinkedListDemo<S, T>[]) new Object[10];
Does anyone know how the Java HashMap class circumvents this issue and / or how can I? I tried to create an intermediate variable inside the constructor, as indicated in the link above, but that didn't work.
source share