Chapter 14
Generic Class
                      What Are Generics?
 Generics abstract over Types.
 Classes, Interfaces and Methods can be Parameterized by
      Types.
 Generics provide increased readability and type safety.
11/11/2024 12:08 PM       Dipankar Dutta, UIT, BU           12.2
                       Generics (Cont’d)
 A class definition with a type parameter is stored in a file and
      compiled just like any other class.
 Once a parameterized class is compiled, it can be used like any
      other class.
        However, the class type plugged in for the type parameter
            must be specified before it can be used in a program.
        Doing this is said to instantiate the generic class.
              Sample<String> object = new Sample<String>();
11/11/2024 12:08 PM           Dipankar Dutta, UIT, BU               12.3
A Class Definition with a Type Parameter
11/11/2024 12:08 PM   Dipankar Dutta, UIT, BU   12.4
A Class Definition with a Type Parameter
                 (Cont’d)
 A class that is defined with a parameter for a type is called a
      generic class or a parameterized class
        The type parameter is included in angular brackets after the
            class name in the class definition heading.
        Any non-keyword identifier can be used for the type
            parameter, but by convention, the parameter starts with an
            uppercase letter.
        The type parameter can be used like other types used in the
            definition of a class.
11/11/2024 12:08 PM             Dipankar Dutta, UIT, BU              12.5
    Generic Class Definition: An Example
11/11/2024 12:08 PM   Dipankar Dutta, UIT, BU   12.6
     Generic Class Definition: An Example (Cont’d)
11/11/2024 12:08 PM   Dipankar Dutta, UIT, BU        12.7
            Generic Class Usage: An Example
11/11/2024 12:08 PM    Dipankar Dutta, UIT, BU   12.8
              Generic Class Usage: An Example (Cont’d)
Program Output:
     11/11/2024 12:08 PM    Dipankar Dutta, UIT, BU      12.9
                                     Lists
 list: an ordered sequence of elements, each accessible by a 0-
      based index (array index started with 0)
        one of the most basic collections of data
11/11/2024 12:08 PM           Dipankar Dutta, UIT, BU              12.10
                      The ArrayList class
 Class ArrayList<E> implements the notion of a list using a
      partially-filled array
        when you want to use ArrayList, remember to
         import java.util.*;
11/11/2024 12:08 PM            Dipankar Dutta, UIT, BU
                                                         11    12.11
                        ArrayList features
 Think of it as an auto-resizing array that can hold any type of object,
   with many convenient methods
 Maintains most of the benefits of arrays, such as fast random access
 Frees us from some tedious operations on arrays, such as sliding
   elements and resizing
 Can call toString on an ArrayList to print its elements
     [1, 2.65, Marty Stepp, Hello]
  11/11/2024 12:08 PM       Dipankar Dutta, UIT, BU                  12.12
                        Generic classes
 ArrayList<E> is a generic class.
        The <E> is a placeholder in which you write the type of elements
         you want to store in the ArrayList.
 Example:
       ArrayList<String> words = new ArrayList<String>();
        Now the methods of words will manipulate and return Strings.
11/11/2024 12:08 PM           Dipankar Dutta, UIT, BU                       12.13
                      ArrayList vs. array
 array
       String[] names = new String[5];
       names[0] = "Jennifer";
       String name = names[0];
 ArrayList
       ArrayList<String> namesList = new
         ArrayList<String>();
       namesList.add("Jennifer");
       String name = namesList.get(0);
11/11/2024 12:08 PM       Dipankar Dutta, UIT, BU   12.14
                           Adding elements
 Elements are added dynamically to                       the list:
   ArrayList<String> list = new                           ArrayList<String>();
   System.out.println("list = "                           + list);
   list.add("Tool");
   System.out.println("list = "                           + list);
   list.add("Phish");
   System.out.println("list = "                           + list);
   list.add("Pink Floyd");
   System.out.println("list = "                           + list);
 Output:
   list =             []
   list =             [Tool]
   list =             [Tool, Phish]
   list =             [Tool, Phish, Pink Floyd]
11/11/2024 12:08 PM             Dipankar Dutta, UIT, BU                          12.15
                      Removing elements
 Elements can also be removed by index:
   System.out.println("before remove list = " + list);
   list.remove(0);
   list.remove(1);
   System.out.println("after remove list = " + list);
 Output:
   before remove list = [Tool, U2, Phish, Pink Floyd]
   after remove list = [U2, Pink Floyd]
        Notice that as each element is removed, the others shift downward
         in position to fill the hole.
        Therefore, the second remove gets rid of Phish, not U2.
                 index
                 index   0
                         0    11 1 2 2        3
                 value
                 value Tool  U2 Floyd
                        U2 Phish
                            Pink  Phish  Pink Floyd
                                   Pink Floyd
11/11/2024 12:08 PM           Dipankar Dutta, UIT, BU                   12.16
                      Searching for elements
 You can search the list for particular elements:
   if (list.contains("Phish")) {
       int index = list.indexOf("Phish");
       System.out.println(index + " " +
     list.get(index));
   }
   if (list.contains("Madonna")) {
       System.out.println("Madonna is in the list");
   } else {
       System.out.println("Madonna is not found.");
   }
 Output:
   2 Phish
   Madonna is not found.
 contains tells you whether an element is in the list or not,
      and indexOf tells you at which index you can find it.
11/11/2024 12:08 PM         Dipankar Dutta, UIT, BU           12.17
                          ArrayList methods
  Method name                                         Description
add(value)                adds the given value to the end of the list
add(index, value)         inserts the given value before the given index
clear()                   removes all elements
contains(value)           returns true if the given element is in the list
get(index)                returns the value at the given index
indexOf(value)     returns the first index at which the given element
                   appears in the list (or -1 if not found)
lastIndexOf(value) returns the last index at which the given element
                   appears in the list (or -1 if not found)
remove(index)      removes value at given index, sliding others back
size()                    returns the number of elements in the list
    11/11/2024 12:08 PM          Dipankar Dutta, UIT, BU                     12.18
A Generic Constructor Name Has No Type
             Parameter!!!
   Although the class name in a parameterized class definition
       has a type parameter attached, the type parameter is not used
       in the heading of the constructor definition:
               public Pair<T>()
   A constructor can use the type parameter as the type for a
       parameter of the constructor, but in this case, the angular
       brackets are not used:
               public Pair(T first, T second)
   However, when a generic class is instantiated, the angular
       brackets are used:
               Pair<String> pair = new Pair<String>("Happy", "Day");
 11/11/2024 12:08 PM              Dipankar Dutta, UIT, BU              12.19
A Primitive Type Cannot be Plugged in for a
             Type Parameter!!!
   The type plugged in for a type parameter must always be a
      reference type:
         It cannot be a primitive type such as int, double, or char
         However, now that Java has automatic boxing, this is not a big
          restriction. Autoboxing is the automatic conversion that the Java
          compiler makes between the primitive types and their corresponding
          object wrapper classes. For example, converting an int to an Integer,
            a double to a Double, and so on.
         Note: Reference types can include arrays.
  11/11/2024 12:08 PM            Dipankar Dutta, UIT, BU                     12.20
          Simple Example of Autoboxing
Autoboxing converts primitive data types into their corresponding
wrapper classes.
class BoxingExample1
{
             public static void main(String args[])
             {
                      int a=50;
                      Integer a2=new Integer(a);//Boxing
                      Integer a3=5;//Boxing
                      System.out.println(a2+" "+a3);
             }
}
11/11/2024 12:08 PM               Dipankar Dutta, UIT, BU           12.21
             Simple Example of Unboxing
Unboxing in Java refers to the process of converting a wrapper class
object (an object that encapsulates a primitive data type) into its
corresponding primitive data type.
class UnboxingExample1
{
             public static void main(String args[])
             {
                      Integer i=new Integer(50);
                      int a=i;
                      System.out.println(a);
             }
}
11/11/2024 12:08 PM              Dipankar Dutta, UIT, BU          12.22
  Limitations on Type Parameter Usage
 Within the definition of a parameterized class definition, there are
   places where an ordinary class name would be allowed, but a type
   parameter is not allowed.
 In particular, the type parameter cannot be used in simple
   expressions using new to create a new object
     For instance, the type parameter cannot be used as a constructor
         name or like a constructor:
           T object = new T();
           T[] a = new T[10];
  11/11/2024 12:08 PM         Dipankar Dutta, UIT, BU              12.23
Limitations on Generic Class Instantiation
  Arrays such as the following are illegal:
       Pair<String>[] a =
         new Pair<String>[10];
  Although this is a reasonable thing to want to do, it is not allowed
     given the way that Java implements generic classes.
 11/11/2024 12:08 PM        Dipankar Dutta, UIT, BU                  12.24
      Using Generic Classes and Automatic Boxing
11/11/2024 12:08 PM   Dipankar Dutta, UIT, BU      12.25
Using Generic Classes and Automatic Boxing
                  (Cont’d)
Program Output:
     11/11/2024 12:08 PM   Dipankar Dutta, UIT, BU   12.26
                       Multiple Type Parameters
 A generic class definition can have any number of type parameters.
     Multiple type parameters are listed in angular brackets just as in the
      single type parameter case, but are separated by commas.
 11/11/2024 12:08 PM           Dipankar Dutta, UIT, BU                    12.27
      Multiple Type Parameters (Cont’d)
11/11/2024 12:08 PM   Dipankar Dutta, UIT, BU   12.28
      Multiple Type Parameters (Cont’d)
11/11/2024 12:08 PM   Dipankar Dutta, UIT, BU   12.29
Using a Generic Class with Two Type
            Parameters
                      Program Output:
11/11/2024 12:08 PM               Dipankar Dutta, UIT, BU   12.30
     A Generic Classes and Exceptions
 It is not permitted to create a generic class with Exception,
   Error, Throwable, or any descendent class of Throwable
      A generic class cannot be created whose objects are
          throwable
           public class GEx<T> extends Exception
      The above example will generate a compiler error message
 11/11/2024 12:08 PM       Dipankar Dutta, UIT, BU                12.31
                Bounds for Type Parameters
 Sometimes it makes sense to restrict the possible types that can be
  plugged in for a type parameter T.
    For instance, to ensure that only classes that implement the
        Comparable interface are plugged in for T, define a class as
        follows:
          public class RClass<T extends Comparable>
    "extends Comparable" serves as a bound on the type
        parameter T.
    Any attempt to plug in a type for T which does not implement the
        Comparable interface will result in a compiler error message.
   11/11/2024 12:08 PM        Dipankar Dutta, UIT, BU                   12.32
       Bounds for Type Parameters (Cont’d)
 A bound on a type may be a class name (rather than an interface
   name)
     Then only descendent classes of the bounding class may be plugged in for the
      type parameters:
    public class ExClass<T extends Class1>
 A bounds expression may contain multiple interfaces and up to one
   class.
 If there is more than one type parameter, the syntax is as follows:
    public class Two<T1         extends          Class1,   T2   extends   Class2   &
      Comparable>
   11/11/2024 12:08 PM           Dipankar Dutta, UIT, BU                           12.33
    Bounds for Type Parameters (Cont’d)
11/11/2024 12:08 PM   Dipankar Dutta, UIT, BU   12.34
                         Generic Interfaces
 An interface can have one or more type parameters.
 The details and notation are the same as they are for classes with
  type parameters.
   11/11/2024 12:08 PM       Dipankar Dutta, UIT, BU              12.35
                         Generic Methods
 When a generic class is defined, the type parameter can be used in
  the definitions of the methods for that generic class.
 In addition, a generic method can be defined that has its own type
  parameter that is not the type parameter of any class
     A generic method can be a member of an ordinary class or a member of a
      generic class that has some other type parameter.
     The type parameter of a generic method is local to that method, not to the class.
  11/11/2024 12:08 PM             Dipankar Dutta, UIT, BU                            12.36
                        Generic Methods (Cont’d)
 The type parameter must be placed (in angular brackets) after all the
   modifiers, and before the returned type:
     public static <T> T genMethod(T[] a)
 When one of these generic methods is invoked, the method name is
   prefaced with the type to be plugged in, enclosed in angular brackets
     String s = NonG.<String>genMethod(c);
  11/11/2024 12:08 PM          Dipankar Dutta, UIT, BU               12.37
         Inheritance with Generic Classes
 A generic class can be defined as a derived class of an ordinary
   class or of another generic class
     As in ordinary classes, an object of the subclass type would
         also be of the superclass type
 Given two classes: A and B, and given G: a generic class, there is
   no relationship between G<A> and G<B>
     This is true regardless of the relationship between class A and
         B, e.g., if class B is a subclass of class A
 11/11/2024 12:08 PM           Dipankar Dutta, UIT, BU             12.38
    A Derived Generic Class: An Example
11/11/2024 12:08 PM   Dipankar Dutta, UIT, BU   12.39
           A Derived Generic Class: An Example (Cont’d)
Program Output:
11/11/2024 12:08 PM        Dipankar Dutta, UIT, BU        12.40
End of Chapter 14
     Questions?