CS计算机代考程序代写 Java SWEN20003 Object Oriented Software Development

SWEN20003 Object Oriented Software Development

SWEN20003
Object Oriented Software Development

Generics

Semester 1, 2002

Generics SWEN20003 Semester 1, 2002 1 / 20

Recap & today’s lecture – Generics

Recap on last lecture:

Comparable interface

How to use ArrayList

T is a type parameter, can be given to a class. How about generics
for a function?.

Why generics? Well, to allow code-reuse

Today’s lecture:

Defining generics

Wildcard and subtyping

Generics SWEN20003 Semester 1, 2002 2 / 20

Defining a Generic Class

Keyword

Generic Class: A class that is defined with an arbitrary type for a field,
parameter or return type.

The type parameter is included in angular brackets after the class
name in the class definition heading.

A type parameter can have any reference type (i.e., any class type)
plugged in.

Traditionally, a single uppercase letter is used for a type parameter,
but any non-keyword identifier may be used.

A class definition with a type parameter is stored in a file and
compiled just like any other class.

Generics SWEN20003 Semester 1, 2002 3 / 20

Defining Generics

public class Sample {

private T data;

public void setData(T data) {

this.data = data;

}

public T getData() {

return data;

}

}

Generics SWEN20003 Semester 1, 2002 4 / 20

Defining a Generic Class – Multiple Types

public class TwoTypePair {

private T1 first;

private T2 second;

public TwoTypePair() {

first = null;

second = null;

}

public TwoTypePair(T1 first, T2 second) {

this.first = first;

this.second = second;

}

public void setFirst(T1 first){

this.first = first;

}

public void setSecond(T2 second) {

this.second = second;

}

// Additional methods go here

}

Generics SWEN20003 Semester 1, 2002 5 / 20

Using a Generic Class – Multiple Types

import java.util.Scanner;

public class TwoTypePairDemo {

public static void main(String[] args) {

TwoTypePair rating =

new TwoTypePair(“The Car Guys”, 8);

Scanner keyboard = new Scanner(System.in);

System.out.println(“Our current rating for ” +

rating.getFirst() + ” is ” + rating.getSecond());

System.out.println(“How would you rate them?”);

int score = keyboard.nextInt();

rating.setSecond(score);

System.out.println(“Our new rating for “+

rating.getFirst() + ” is ” + rating.getSecond());

}

}

Generics SWEN20003 Semester 1, 2002 6 / 20

Subtyping

Keyword

Generics’ subtyping: Generic classes or interfaces are not related merely
because there is a relationship between their type parameters.

abstract class Animal {}

class Dog extends Animal {}

class Bear extends Animal {}

Dog dog = new Dog();

Animal a = dog; // OK

List dogs = new ArrayList();

List animals = new ArrayList();

dogs = animals; (1) // Compile-time error

animals = dogs; (2) // Compile-time error

Generics SWEN20003 Semester 1, 2002 7 / 20

Subtyping

abstract class Animal {}

class Dog extends Animal {}

class Bear extends Animal {}

Dog dog = new Dog();

Animal a = dog; // OK

List dogs = new ArrayList();

List animals = new ArrayList();

animals.add(new Bear()); // Add a Bear in to animals

dogs = animals; (1) // Assume this is OK, then …

Dog dog = dogs.get(0) // Opps, we should get a dog out of dogs,

// but what we actually get is a bear.

(1) is not allowed because doing so allows to pull out elements in animals
which can be of either type Bear or Dog. But the dogs list is supposed to
only contain Dog elements.

Generics SWEN20003 Semester 1, 2002 8 / 20

Wildcard and subtyping

abstract class Animal {}

class Dog extends Animal {}

class Bear extends Animal {}

List dogs = new ArrayList();

List animals = new ArrayList();

animals = dogs; (2) // Assume this is OK, then …

animals.add(new Bear()); // Add a bear to animals. Opps, this in

// turn adds a bear to dogs because of

// object reference at (2).

(2) is not allowed because doing so allows to add/write new elements in
animals which in turn will add the elements to dogs via the object
reference. The new elements added to animals can be of either type Bear
or Dog. But the dogs list is supposed to only contain Dog elements.

Generics SWEN20003 Semester 1, 2002 9 / 20

Wildcard

Although Dog is a subtype of Animal, the generic collection
List is not a subtype of List. In fact, the common
parent of them is List, wherein the ? is a wildcard that stands
for unknown type.

Generic wildcards target two primary needs: reading from and
inserting to a generic collection.

Three ways to define a collection using generic wildcards.

List listUnknown = new ArrayList();

List listUnknown = new ArrayList();

List listUnknown = new ArrayList();

Generics SWEN20003 Semester 1, 2002 10 / 20

The Unkown Wildcard

The List means a list is typed to an unknown type. This could
be a list of any type.

Since we do not know the type of the list, we can only read the
collection.

public void print(List myList){

for(Object o: myList){ // o could be of any type

System.out.println(o);

}

}

List dogs = new ArrayList();

print(dogs);

List bears = new ArrayList();

print(bears);

This can be thought of as read-only collection

Generics SWEN20003 Semester 1, 2002 11 / 20

The Extends Wildcard

The List means a list of objects that are instances
of the class A, or subclasses of A.

Since we do know the type of elements of the list is A or subclasses of
A, it is safe to read the list and cast its elements to type A.

public void print(List myList){

for(Animal a: myList){

System.out.println(a);

}

}

List dogs = new ArrayList();

print(dogs);

List bears = new ArrayList();

print(bears);

This can be thought of as read-only collection

Generics SWEN20003 Semester 1, 2002 12 / 20

The Super Wildcard

The List means a list of objects that are instances of
the class A, or superclasses of A.

Since we do know the type of elements of the list is A or superclasses
of A, it is safe to insert elements of type A or subclasses of A to the
list.

public void insert(List myList){

myList.add(new Dog());

myList.add(new Bear());

}

List animals = new ArrayList();

insert(animals);

Object o = animals.get(0); // OK

Animal a = animals.get(0) // Not OK

List objects = new ArrayList();

insert(objects);

Generics SWEN20003 Semester 1, 2002 13 / 20

Subtyping – continue

Upcasting and downcasting types:

abstract class Animal {}

class Dog extends Animal {}

class Bear extends Animal {}

Dog dog = new Dog();

Animal a = (Animal) dog;// upcasting Dog -> Animal

Animal b = new Dog();

Dog d = (Dog) b; // downcasting Animal -> Dog

Animal c = new Animal(){…};

Dog e = (Dog) c; // Runtime error: ClassCastException

// c could be a bear, which can’t

// be cast to a dog.

Generics SWEN20003 Semester 1, 2002 14 / 20

Subtyping – continue

In general, T1 <: T2 if T1 <: T2, where <: denotes is subtype of. Now let’s consider: ArrayList arrayListStr = new ArrayList();

List listStr = arrayListStr; // Is this OK?

In this case, it’s fine. Since ArrayList is subtype of List, we have
ArrayList as subtype of List. Thus,
“List listStr = arrayListStr” is upcasting type from
ArrayList to List.

Generics SWEN20003 Semester 1, 2002 15 / 20

Generic Methods

Keyword

Generic Method: A method that accepts arguments, or returns objects, of
an arbitrary type.

A generic method can be defined in any class. The type parameter (e.g.
T) is local to the method.

public int genericMethod(T arg); // Generic argument

public T genericMethod(String name); // Generic return value

public T genericMethod(T arg); // Both!

public T genericMethod(S arg); // Both!

Generics SWEN20003 Semester 1, 2002 16 / 20

Assess Yourself

Write a generic method that accepts two arguments:

array: an array of elements whose type is T

item: an object of the same type as the array’s elements

The method should return a count of how many times item appears in
array.

Generics SWEN20003 Semester 1, 2002 17 / 20

Assess Yourself

public class TestGenericMethods {

public static void main(String[] args) {

Integer[] nums = {1, 3, 6, 9, 3, 5, 9, 3, 5, 42, null};

String[] names = {“Jon”, “Arya”, “Dany”, “Tyrion”, “Jon”};

System.out.println(countOccurrences(nums, 3));

System.out.println(countOccurrences(names, “Jon”));

}

public static int countOccurrences(T[] array, T item) {

int count = 0;

if (item == null) {

for (T arrayItem : array){

count = arrayItem == item ? count + 1 : count;

}

} else {

for (T arrayItem : array){

count = item.equals(arrayItem) ? count + 1 : count;

}

}

return count;

}

}

Generics SWEN20003 Semester 1, 2002 18 / 20

Pitfall: What Can’t We Do?

Generic programming is powerful, but has its limitations. When using
generics, we can’t:

Instantiate parametrized objects

T item = new T();

Create arrays of parametrized objects

T[] elements = new T[];

Otherwise, most things are fair game.

Generics SWEN20003 Semester 1, 2002 19 / 20

Learning Outcomes

You should be able to:

Understand generic classes in Java

Use generically typed classes

Define generically typed classes

Understand generics’ subtyping

Generics SWEN20003 Semester 1, 2002 20 / 20