0

HashMap<K,V> stores data as array of entry. i.e

Entry<K,V>[] table

and type of key and value inside Entry are K and V respectively.

But..

ArrayList<E> stores data as array of object. i.e.

Object[] elementData

So wondering why ArrayList doesn't use array of type E ??

rai.skumar
  • 9,001
  • 5
  • 37
  • 54

1 Answers1

4

Short answer: try implementing it yourself and see what happens. Long answer: because Java uses type erasure, and you need to know the type at run time in order to create a new array, new E[size] won't compile, so it can't do this without some kind of hack. You don't need to know generic parameters to create a new array, however, as they're erased so you don't have to know them at runtime.

Jules
  • 13,417
  • 7
  • 75
  • 117