"

Summary

How to Use Generics?

  1. Create a generic class: public class GenericClass<T> { … }
  2. Instantiate the object. Each of Type parameter (in this case, it is T) is replaced with the Integer type.
    GenericClass<Integer> integerObject = new GenericClass<Integer>();
  3. Generics can also be used within constructors to pass type parameters for class field initialization.
    GenericClass ob1 = new GenericClass(3); GenericClass ob2 = new GenericClass("Georgia");
  4. Generics has raw type for backward compatibility. It will eliminate type-checking at compile time.
    GenericClass rawRef = new GenericClass();
  5. Generics does not support sub-typing
    List<Number> numbers = new ArrayList<Integer>(); // won’t compile.
    Integer isa subtype of Number. The correct declaration is
    List<Integer> numbers = new ArrayList<Integer>();

In a nutshell, the key benefit of generics is to enable errors to be detected at compile time rather than at runtime (ensuring compile-time safety). A generic class or method permits you to specify allowable types of objects that the class or method can work with. If you attempt to use an incompatible object, the compiler will detect that error. Generics also helps to reuse the code for any type we want to use.

Java’s Collection library has numerous examples of generic classes and interfaces, specifically Abstract Data Types.  We discussed Stacks and Queues.  A Stack can only be accessed from one end – you push and pop from the same end resulting in a Last-In-First-Out (LIFO) data structure.  A Queue works like a line at the movie theater; the first person in line gets to buy a ticket first.  This is known as a First-In-First-Out (FIFO) data structure.

License

Icon for the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License

Computer Science II Copyright © by Various is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, except where otherwise noted.