CS102 · Annotated SlidesGenerics — Generic Classes and Methods
Generics · Annotated slides

Generic Classes and Methods

Why generics (one method or class for many types, checked at compile time), generic methods such as printArray and maximum, bounded type parameters (T extends Comparable<T>), and generic classes like Sample<T> and LinkedList<E>.

Slide text Study notes Highlight: key words Tips, tricks & traps Seen again elsewhere How it can come up
Slide 1: Slide 1
Exam weight Low
    Slide 2: Slide 2
    Exam weight Low
      Slide 3: Slide 3
      Exam weight Medium
      1. Generic methods and classes: one declaration for a set of related types, with compile-time type safety.
      Slide 4: Slide 4
      Exam weight Low
      1. Motivation: three overloaded printArray methods differ only in the element type → one generic method.
      Slide 5: Slide 5
      Exam weight High
      1. A generic method declares its type parameter before the return type: public static <T> void printArray(T[] a).
      🎯 How this can come up · 1 question
      MCQ

      Which header declares a generic method?

      Slide 6: Slide 6
      Exam weight Low
        Slide 7: Slide 7
        Exam weight High
        1. To compare with >, the type must be bounded: <T extends Comparable<T>> T maximum(T x, T y, T z).
        Slide 8: Slide 8
        Exam weight Low
          Slide 9: Slide 9
          Exam weight Low
            Slide 10: Slide 10
            Exam weight High
            1. Comparable is the upper bound; the default bound is Object. extends is used even for interfaces.
            🎯 How this can come up · 1 question
            True / False

            In a bounded type parameter you write implements for interfaces, e.g. <T implements Comparable<T>>.

            Slide 11: Slide 11
            Exam weight Low
              Slide 12: Slide 12
              Exam weight Low
                Slide 13: Slide 13
                Exam weight Low
                1. Generic class: class Sample<T> { private T data; … }
                Slide 14: Slide 14
                Exam weight High
                1. Sample<String> s = new Sample<String>(); — the type argument can’t be primitive (use Integer, not int).
                🎯 How this can come up · 1 question
                MCQ

                Which is NOT allowed as a type argument?

                Slide 15: Slide 15
                Exam weight Low
                  Slide 16: Slide 16
                  Exam weight Low
                    Slide 17: Slide 17
                    Exam weight Low
                    1. LinkedList<E> is a generic class; E is the element type.
                    Slide 18: Slide 18
                    Exam weight Low