Generics lecture

14
1 Generics <? super Java> By Brad Bazemore

Transcript of Generics lecture

Page 1: Generics lecture

1

Generics <? super Java>By Brad Bazemore

Page 2: Generics lecture

2

Create... a box interface

− You can put into the box− You can take out of box− NOTE: needs to be able to handle ALL

possible types (not just primitives!)

GO!

Page 3: Generics lecture

3

Generic Programing

generic programming is a style of computer programming

written in terms of to-be-specified-later instantiated when needed for specific

types provided as parameters

Page 4: Generics lecture

4

Ex1

Given N data structures Given M algorithms If we want an algo for every data struct we

wind up with NM methods− NOTE: this is BAD

Using generics we end up with only N+M methods

− NODE: this is GOOD

Page 5: Generics lecture

5

Java Generics

Page 6: Generics lecture

6

What are they for?

"a type or method to operate on objects of various types while providing compile-time type safety." (Java Programming Language)

Basically...

− IT MAKES LIFE BETTER!!!

Page 7: Generics lecture

7

QUIZ!

If my program has 3 types of data structures and 5 types of algorithms...

1)How many methods will there be with NO generics?

2)How many methods will there be WITH generics?

GO!

Page 8: Generics lecture

8

The Syntax

ObjectName <Type Variable> Ex2

− ArrayList<String> L=new ArrayList<String>();

Attention Test

− Create a method signature for the put operation for a box, and it takes a generic of some kind

GO!

Page 9: Generics lecture

9

Lo Pi Hi

Lets take it up a notch! Ok so there is a catch, if I say <Number>

− Integer, Float, ect. It will not work!!! Why you ask? Attention Test

QUIZ!

Page 10: Generics lecture

10

Quiz

How do you implement a method with generic type that accepts all subtypes of Number?

Page 11: Generics lecture

11

Now that I have you attention

The fancy word for this is “variance” But so you can see the big picture Covariant: converting from a specialized

type (Cats) to a more general type (Animals): Every cat is an animal.

Contravariant: converting from a general type (Shapes) to a more specialized type (Rectangles): Is this shape a rectangle?

Invariant: not able to convert.

Page 12: Generics lecture

12

So how to make this work...

Using the Java wild card “?”− Yes it is the

The basic idea is this− < ? extends T >− < ? super T >

Extends means all subtypes of T Super means all super types of T

Page 13: Generics lecture

13

Ex3

Page 14: Generics lecture

14

See?

Any Questions?

NOTE: there is a lab