Docsity

Generic Programming: Defining Constructs for Different Data Types in Java - Prof. Nelson P, Study notes of Computer Science

Partial preview of the text

Download Generic Programming: Defining Constructs for Different Data Types in Java - Prof. Nelson P and more Study notes Computer Science in PDF only on Docsity!

CMSC 132:

Object-Oriented Programming II

Generic Programming

Department of Computer Science

University of Maryland, College Park

Generic Programming

Generic programming

Defining constructs that can be used with different

data types

I.e., using same code for different data types

Implemented in Java through

1. Inheritance  A extends B

2. Type variables 

Generic Class

Class with one or more type variables

Example  class ArrayList

To use generic class, provide an actual type

Valid types

Class  ArrayList

Interface  ArrayList

Invalid types

Primitive type  ArrayList

(use wrappers)  ArrayList

Defining a Generic Class

Append type variable(s) to class name Use angle brackets  ClassName Can use any name for type variable But typically single uppercase letter  E, K, V, etc… Use the type variable to define Type of variables Type of method parameters Method return type Object allocation Arrays Type of an array object may not be a type variable or a parameterized type, unless it is an unbounded wildcard type How to define arrays? T[] data = (T[]) new Object [size];

Generics and Subtyping

In general if B is a subtype of A, and GT is a generic type declaration it is not the case that GT is a subtype of GT Example ArrayList strL = new ArrayList(); ArrayList objL = strL; // Illegal!

8

Generics and Subtyping

Consider what could happen if legal

class A { … } class B extends A { … } // B is subtype of A List bL = new ArrayList(); List aL = bL; aL.add(new A()); B b = bL.get(0); // runtime exception

Using String Class

ArrayList sL = new ArrayList(); ArrayList oL = sL ; // Illegal, but let’s assume is valid oL.add(new Integer(10)); String entry = sL.get(0); // Problem!!

Wildcards

? (unknown) Collection Collection whose element type matches anything Bounded Wildcard Example: ArrayList Unknown type that is Shape or subtype of Shape Summary unknown type  unknown type that is typeExpression or a subtype of typeExpression  unknown type that is typeExpression or a supertype of typeExpression. typeExpression can involve further occurrences of wildcard type expressions Example (WildCard class in code distribution)