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 anObject-based one - Override
equalsto give a type value equality, in place of=='s default reference comparison - Implement
Comparableto give a type a natural ordering, and implementComparatorwhen 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
- Why Generics?
- Why Not Just Store Object?
- A Generic DynamicArray
- The Array Problem
- Using It
- The Trouble with Primitives
- Comparing Elements:
equalsvs== - Defining Equality for Student
- Ordering Elements: Comparable
- Making Student Comparable
- A Generic ArrayUtils
- Sorting, Generically
- Custom Orderings: Comparator
- Sorting with a Comparator
- Overloading remove: by Index or by Value
- The
DynamicArray<Integer>Trap