14 February 2022

Squirrely Stuff about Generics

ArrayList< String> al = new ArrayList<>();
ArrayList< Integer> bl = new ArrayList<>();
ArrayList< ArrayList<String>> bl = new ArrayList<>();



/**************************************************
*   Author: Morrison
*   Date:  14 Feb 202022
**************************************************/
import java.util.ArrayList;
public class OldWays 
{
    public OldWays()
    {
    }
    
    public static void main(String[] args)
    {
        ArrayList al = new ArrayList();
        al.add("cowabunga");
        al.add(new Integer(5));
        System.out.println(al.get(0));
        System.out.println(al.get(1));
        System.out.println(((String)al.get(0)).length());
        System.out.println(((Integer)al.get(1)).doubleValue());
    }
}

No arrays! You cannot construct arrays of generic type, but you ahve seen the workaroud

Type Erasure Generics are implemented via Type erasure. In compilation:

  1. The compiler performs static type checking.
  2. The compiler performs the "old ways" casts. It gurantees that these casts are valid. You can break this guarantee by doing unsafe opearations. You can silence these wiht @SuppressWarnings("unchecked")
  3. All of the generics are erased (the < .... > stuff.

Types, Subtypes, and Generics What is a type?

concrete classes define types
abstract classes define types
interfaces define types

S is a subtype of T if
    if S and T are classes and S extends T.
    if S and T are interfaces and S extends T.
    If S is a class, T an interface, and S extends T.
Suppose Quack<T> is a generic class.
If S is a subtype of T, and S is NOT T then Quack<S>
is NOT a subtype of Quack<T>.

However
S[] is a subtype of T[]

Type Bounds