Tuesday, September 10, 2013

Generic data structures in java

Suppose we have a stack of string, but later we want to use it for integers. We have to re-write the code again and again for every data type. So how can we solve this.

Attempt 1 - Creating the stack for every data type, which is very exhaustive and needs code changes again.

Attempt 2 - Implement a stack using Object class.

Downside -

  • Discover type mismatch errors at run time
  • Casting has to be done at client side
  • Code looks ugly because of so many castings
Attempt 3 - Java generics



Post a Comment