Docsity

COP3330 Fall 2006 Class Notes: Generic Classes, TreeSet, PriorityQueue, and Enumerations, Study notes of Computer Science

Partial preview of the text

Download COP3330 Fall 2006 Class Notes: Generic Classes, TreeSet, PriorityQueue, and Enumerations and more Study notes Computer Science in PDF only on Docsity!

Useful Classes

COP3330 – Fall 2006

University of Central Florida

H. Schwartz

Outline

• Generic Classes

• TreeSet

• PriorityQueue

• Enumerations

COP 3330 – Fall 2006

Generic Classes

• Classes with type parameters.

– Generic in the sense that we do not know

what type we will be working with.

• Also called “generic polymorphism”

– Allows a method to do different things

(does not involve inheritance in this

case)

COP 3330 – Fall 2006

Generic Classes

• Example (from book):

Source: Cohoon and Davidson. Java 5.0 Program Design COP 3330 – Fall 2006

class Wrapper { //instance variable private T tValue;

public Wrapper(T t){ tValue = t; //constructor, t and tValue type are same }

public T get(){ return tValue; //accessor method }

public void set(T t){ tValue = t; //mutator method (changes values) }

public String toString(){ return tValue.toString(); //text representation } }

PriorityQueue

• Queue: an ordered structure with one item which

may be accessed/removed directly.

– FIFO

– LIFO (stack)

– Based on priority (comparison)

• PriorityQueue: order based on priority

(Objects in queue must implement Comparable)

COP 3330 – Fall 2006

PriorityQueue

• Methods: is type

– boolean offer(E o)

– boolean add(E o)

– E peek()

– E poll()

– boolean remove (E o)

– int size()

COP 3330 – Fall 2006

PriorityQueue

• Example:

COP 3330 – Fall 2006

//assume we have a class ToDoItem which implements comparable: //has a string and priority number, higher = more priority … PriorityQueue tdList = new PriorityQueue();

//populate with things to do: tdList.offer(new ToDoItem(“Cut my hair”, 10); tdList.offer(new ToDoItem(“Teach a course”, 2); … //find out next thing to do ToDoItem nextTD = tdList.poll(); while (nextTD != null){ System.out.println(tdList); //calls toString to print item waitForKey(); nextTD = tdList.poll(); }

Enumerations

• class Enum

– super class of all “enums”

– enums are built in as part of syntax

• Good for storing a list of things which could be a

class, but wouldn’t have methods.

– Comparing with self

COP 3330 – Fall 2006