Generics

This chapter makes DynamicArray generic so one class works for any element type, and covers equality (equals), natural ordering (Comparable), external ordering (Comparator), and method overloading.

After reading this chapter, you should be able to:

  • Make a class generic with a type parameter, DynamicArray<T>, and explain why generics fix the duplication of a type-specific structure and the lost type safety of an Object-based one
  • Override equals to give a type value equality, in place of =='s default reference comparison
  • Implement Comparable to give a type a natural ordering, and implement Comparator when a different, external ordering is needed
  • Overload a method, and explain how Java picks which version runs based on the argument’s declared type

You can download the accompanying code for this chapter: starter and solution.

Notes

  1. Why Generics?
  2. Why Not Just Store Object?
  3. A Generic DynamicArray
  4. The Array Problem
  5. Using It
  6. The Trouble with Primitives
  7. Comparing Elements: equals vs ==
  8. Defining Equality for Student
  9. Ordering Elements: Comparable
  10. Making Student Comparable
  11. A Generic ArrayUtils
  12. Sorting, Generically
  13. Custom Orderings: Comparator
  14. Sorting with a Comparator
  15. Overloading remove: by Index or by Value
  16. The DynamicArray<Integer> Trap