Skip to the content.

Generics

-

Generics

-

Generics - a FIFO Queue

-

Hmm.

-

Queue

this is an imaginary example…

// Pretend Queue has a add() method and a next() method.
Queue personQueue = new Queue<Person>(); // this queue is for persons

personQueue.add(joe); // joe starts standing in line
currentPerson = personQueue.next();  // "Next!" person being serviced

Queue carWashQueue = new Queue<Vehicle>(); // this queue tracks cars to be washed
carWashQueue.add(teslaS);

-

Terms

-

Examples of generic Types

-

Primitive types cannot be type parameters

Example:

// This will not compile!!!!

public class Main{
  public static void main(String[] args){
    ArrayList<int> primitiveArrayList = new ArrayList<>();
  }
}

-

The solution? Wrapper classes!


public class Main{
  public static void main(String[] args){
    ArrayList<Integer> pg = new ArrayList<>();
  }
}

-

Primitives and autoboxing

public static void main(String[] args){
  int x, y;
  x = 5;
  ArrayList<Integer> box = new ArrayList<>();
  box.add(x);
  y = box.get(0);
  System.out.println(y);

-