• No results found

CSCI 241. Scott Wehrwein. Java Miscellanea: Generic Classes Inner Classes The Comparable interface

N/A
N/A
Protected

Academic year: 2021

Share "CSCI 241. Scott Wehrwein. Java Miscellanea: Generic Classes Inner Classes The Comparable interface"

Copied!
19
0
0

Loading.... (view fulltext now)

Full text

(1)

CSCI 241

Scott Wehrwein

Java Miscellanea: Generic Classes

Inner Classes

(2)

Goals

Know why Java has

generics

, and how to use

and implement generic classes.

Understand how to use an

inner class

.

Know how the

Comparable

interface

works.

Note: The Java-specific material in this segment is important for understanding some of the coming concepts and is heavily used in A2 and A3. It will not be directly tested on exams.

(3)

/** A collection that contains no duplicate * elements. */

interface Set {

/** Return true if the set contains ob */

boolean contains(Object ob);

/** Add ob to the set; return true iff * the collection changed. */

boolean add(Object ob);

/** Remove ob from the set; return true iff * the collection is changed. */

boolean remove(Object ob);

... }

Reminder: The

Set ADT

Can contain anything that extends Object (any class at all)

(4)

The Problem

Set c = ... c.add(“Hello”) c.add(“World”); ... for (Object ob : c) {

  String s = (String) ob;

  // do things with s } String[] a = ... a[0] = “Hello” a[1] = “World”; ...

for (int i = 0; i < a.length; i++) { String s = a[i];

  // do things with s;

}

Notice: Arrays don’t have this problem! If you want a Set of

(5)

The Solution:

Generics

Object[] oa = ...          // array of Objects

String[] sa =  ...         // array of Strings

ArrayList<Object> oA = ... // ArrayList of Objects

ArrayList<String> sA = ... // ArrayList of Strings

interface Set<T> {

/** Return true iff the collection contains x */

boolean contains(T x);

/** Add x to the collection; return true iff * the collection is changed. */

boolean add(T x);

/** Remove x from the collection; return true iff * the collection is changed. */

boolean remove(T x); ...

}

(6)

The Solution: Generics

The Set interface is now written like this:

Key idea: I don’t need to know what T is to implement these!

interface Set<T> {

/** Return true iff the collection contains x */

boolean contains(T x);

/** Add x to the collection; return true iff * the collection is changed. */

boolean add(T x);

/** Remove x from the collection; return true iff * the collection is changed. */

boolean remove(T x); ...

(7)

The Solution: Generics

Set<String> c = ...

c.add(“Hello”)  /* Okay */

c.add(1979);    /* Illegal: compile error! */

Key idea: I don’t need to know what T is to implement these!

Generally speaking,

   Collection<String>

behaves like the parameterized type

Collection<T>

(8)

The Solution: Generics

Collection<int> c = ...

The bummer: T must extend Object - no primitive types.

Can’t do:

Have to use:

   Collection<Integer>

Java often seamlessly converts int to Integer and back. Integer x = 5; // works

int x = new Integer(5); // works

(9)
(10)

/** A collection that contains no duplicate * elements. */

interface Set<T> {

/** Return true if the set contains ob */

boolean contains(T ob);

/** Add ob to the set; return true iff * the collection is changed. */

boolean add(T ob);

/** Remove ob from the set; return true iff * the collection is changed. */

boolean remove(T ob);

... }

(11)

An example generic class:

ArraySet<T>

class ArraySet<T> implements Set<T> {

T[] a;

int size;

/** Return true iff the collection contains x */

boolean contains(T x) {

for (int i = 0; i < size; i++) {

if a[i].equals(x)

return true;

}

return false;

}

/** Add x to the collection; return true iff * the collection is changed. */

boolean add(T x) {

if (!contains(x)) {

a[size] = x; // let’s hope a is big enough...

size++;

return true;

}

return false;

(12)

Inner Classes

We often use an

inner class

to store Node objects of

trees, graphs, linked lists, etc.

Example: a

Node

class defined inside the

LinkedList

class, only used within the class.

public class LinkedList {

private Node head;

public class Node {

private int value;

private Node next;

}

// methods, etc }

(13)

is (almost) defined like this:

interface Comparable {

int compareTo(Object o); }

(14)

Need to sort students? Builtin

Arrays.sort()

calls

compareTo

instead of using

<

class Student implements Comparable {

// fields and methods

public int compareTo(Object o) {

// compare students by last

// then first name

} }

Student[] my241Section = [...]

Arrays.sort(my241Section);

(15)

The

Comparable

interface

...we can compare apples to oranges!

class

Orange

implements

Comparable;

class

Apple

implements

Comparable;

Orange o =

new

Orange

();

Apple a =

new

Apple

();

a.

compareTo

(o);

interface Comparable {

int compareTo(Object o); }

(16)

The

Comparable

interface

is (actually) defined like this:

interface Comparable<T> {

int compareTo(T o); }

(17)

The Comparable Interface

class Orange implements Comparable<Orange>; class Apple implements Comparable<Apple>;

Orange o = new Orange(); Apple a = new Apple();

a.compareTo(o);

interface Comparable<T> { int compareTo(T o);

}

Won’t compile because Apple doesn’t have:

compareTo(Orange o)

It only has:

(18)

Fancier Generics

SortableCollection<String> c= ... c.sort();

What if I care a little bit what T is?

(19)

Fancier Generics

SortableCollection<String> c= ... c.sort();

What if I care a little bit what T is?

requires T to be Comparable<T>!

interface SortableCollection<T extends Comparable<T>> {

... } 

References

Related documents

This paper includes labor relations in an otherwise standard and parsimonious general equilibrium asset pricing model. Unlike standard Walrasian models, wages incorporate an

Furthermore, while symbolic execution systems often avoid reasoning precisely about symbolic memory accesses (e.g., access- ing a symbolic offset in an array), C OMMUTER ’s test

If breastfeeding by itself doesn’t effectively remove the thickened inspissated milk, then manual expression of the milk, or the use of an efficient breast pump after feeds will

This suggest that developed countries, such as the UK and US, have superior payment systems which facilitate greater digital finance usage through electronic payments compared to

13) Elishiba Njambi Kimani and Donald Kisilu Kombo. An Investigation of Community Participation in the Development of Schools and Income Generating Projects in Rural Areas in

Along these lines, in a model where an incumbent faces a sequence of potential startups and the incumbent’s chance of winning an infringement lawsuit increases with the size of

We show that the average R&amp;D productivity of a firm is decreasing in firm size because the large number of R&amp;D projects run by a large firm becomes a substitute for

12 taken into account when modelling banks, we use different permutations of good inputs – loan loss provisions and equity – and the bad output of non-performing