Day 1

advertisement
COSC 3P40 – Advanced Object-Oriented Programming
COSC 3P40
Advanced Object-Oriented Programming
Super Course
• Instructor: Michael Winter
– Office J323
– email: mwinter@brocku.ca
• Webpage:
www.cosc.brocku.ca/~mwinter/Courses/3P40
© M. Winter
1.1
COSC 3P40 – Advanced Object-Oriented Programming
• Course Description (Brock Calendar):
Advanced object-oriented programming techniques such as graphical
user interfaces, animation, sound, music, networking, parallelism, clientserver and XML using game design as an example. Topics in objectoriented program design including UML and design patterns.
Introduction to advanced Java APIs such as awt, swing, io, nio, sound,
net and xml.
• Prerequisites: two COSC credits or permission of the instructor.
• Java: Java 1.6 or greater and NetBeans
© M. Winter
1.2
COSC 3P40 – Advanced Object-Oriented Programming
Textbooks
• Main Course Material
– SLIDES and NOTES (available through the webpage)
• Supplemental Texts
– Developing Games in Java, D. Brackeen, New Riders (2003),
ISBN 1-5927-3005-1
– Object-Oriented Software Development Using Java, second
edition, Xiaoping Jia, Addison Wesley (2002),
ISBN 0-201-73733-7
© M. Winter
1.3
COSC 3P40 – Advanced Object-Oriented Programming
Course Work
• Marking Scheme
– Project = 4 Programming parts
(done in class/lab, 4x15%)
– Final Exam (Saturday May 10, tba)
60%
40%
• Programming parts 1-4 due by the end of each day (05:00pm)
starting on Tuesday, May 06.
© M. Winter
1.4
COSC 3P40 – Advanced Object-Oriented Programming
Course Outline
Day
Date
Book/Chapt.
Topics
1
May 05
[2]/4,5,6.7,8
Introduction, review of OO concepts, basic
UML, Utility classes, collection classes
2
May 06
[2]/7,8
I/O, Design patterns
3
May 07
[1]/1,[2]/7,8,
11
XML, Threads, multitasking, Concurrency
design patterns
4
May 08
[1]/2,[2]/8
GUI (AWT, Swing), 2D graphics, animation
5
May 09
[1]/3,4,6
Sound effects & music, Network
programming
© M. Winter
1.5
COSC 3P40 – Advanced Object-Oriented Programming
Design principles
Design principles in this course and used by the design patterns
• Use abstraction whenever possible
– introduce (abstract) superclass (or interfaces) in order to implement
or define common behavior
– nothing should be implemented twice
• Program to an interface, not an implementation
• Favor composition over inheritance
– delegation
• Design for change and extension
© M. Winter
1.6
COSC 3P40 – Advanced Object-Oriented Programming
Classes
[ClassModifiers] class ClassName
[extends SuperClass]
[implements Interface1, Interface2, …] {
ClassMemberDeclarations
}
• Class modifiers
– visibility: package versus public
– abstract
– final
• extends clause specifies the superclass
• implements clause specifies the interfaces being implemented
© M. Winter
1.7
COSC 3P40 – Advanced Object-Oriented Programming
Class members
• Class (static) members
– one occurrence for entire class
– shared access by all instances
– if visible, accessed via class name
– public static void main(String[] args) {…}
• Member modifiers
– public versus protected versus package versus private
– abstract
– final
– synchronized (method)
– native (method)
– volatile (field)
– transient (field)
© M. Winter
1.8
COSC 3P40 – Advanced Object-Oriented Programming
Inheritance
• Parent/child, superclass/subclass
• Instances of child inherit data and behaviour of parent
• implements
– inheritance of specification
• extends
– subclassing
– inheritance of code and specification
– overriding
• polymorphism
• Subclass versus subtype
– substitutability
• Subclass as an extension of behavior (specialization)
• Subtype as a contraction of value space (specialization)
© M. Winter
1.9
COSC 3P40 – Advanced Object-Oriented Programming
Subtypes
• a subclass extends the capability of its superclass; the subclass
inherits features from its superclass and adds more features
• every instance of a subclass is an instance of the superclass
• each class defines a type
 Definition: Subtype
Type T1 is a subtype of type T2 if every legitimate value of T1 is
also a legitimate value of T2. In this case, T2 is a supertype of T1.
Substitutability of subtypes:
A value of a subtype can appear wherever a value of its
supertype is expected.
© M. Winter
1.10
COSC 3P40 – Advanced Object-Oriented Programming
Overriding versus Overloading
• Overloading
– methods
– same name, different signatures
– same class or subclass
– effect – multiple methods with same name
– do not overuse (readability of programs)
– overloading should be used only in two situations:
1. When there is a general, non-discriminative description
of the functionality that fits all the overloaded methods.
2. When all the overloaded methods offer the same
functionality, with some of them providing default
arguments.
• Overriding
– instance methods
– same name, signature and result type
– in subclass
– effect – replacement implementation
• access superclass version via super
© M. Winter
1.11
COSC 3P40 – Advanced Object-Oriented Programming
Forms of inheritance
• Inheritance for specification
– parent provides specification
• abstract classes
• interfaces
– behaviour implemented in child
– subtype
• Inheritance for extension
– adding behaviour
– subtype
• Inheritance for specialization
– child is special case
– child overrides behavior to extend
– subtype
© M. Winter
1.12
COSC 3P40 – Advanced Object-Oriented Programming
• Inheritance for construction
– inherit functionality
– ad hoc inheritance
– not a subtype
– use composition
• Inheritance for limitation
– restricting behaviour
– not subtype
– use composition
• Inheritance for combination
– combining behaviours
– multiple inheritance
– only through interfaces in Java
© M. Winter
1.13
COSC 3P40 – Advanced Object-Oriented Programming
Inheritance for Specification: Java interface
Ch.8.4, Budd: Understanding Object-Oriented Programming with Java
interface ActionListener {
public void actionPerformed (ActionEvent e);
}
class CannonWorld extends Frame {
…
// a fire button listener implements the action
// listener interface
private class FireButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
… // action to perform in response to button press
}
}
}
© M. Winter
1.14
COSC 3P40 – Advanced Object-Oriented Programming
Inheritance for Specification: abstract class
Ch.8.4, Budd: Understanding Object-Oriented Programming with Java
public abstract class Number {
public abstract int intValue();
public abstract long longValue();
public abstract float floatValue();
public abstract double doubleValue();
public byte byteValue()
{ return (byte) intValue(); }
public short shortValue()
{ return (short) intValue(); }
}
© M. Winter
1.15
COSC 3P40 – Advanced Object-Oriented Programming
Inheritance for Extension
Ch.8.4, Budd: Understanding Object-Oriented Programming with Java
class Properties extends Hashtable {
…
public synchronized void load(InputStream in)
throws IOException {…}
public synchronized void save(OutputStream out,
String header) {…}
public String getProperty(String key) {…}
public Enumeration propertyNames() {…}
public void list(PrintStream out) {…}
}
© M. Winter
1.16
COSC 3P40 – Advanced Object-Oriented Programming
Inheritance for Specialization
public class MyCar extends Car {
…
public void startEngine() {
motivateCar();
super.startEngine();
}
…
}
© M. Winter
1.17
COSC 3P40 – Advanced Object-Oriented Programming
Inheritance for Construction
Ch.8.4, Budd: Understanding Object-Oriented Programming with Java
class Stack extends LinkedList {
public Object push(Object item)
{ addElement(item); return item; }
public boolean empty()
{ return isEmpty(); }
public synchronized Object pop() {
Object obj = peek();
removeElementAt(size() - 1);
return obj;
}
public synchronized Object peek()
{ return elementAt(size() - 1); }
}
© M. Winter
1.18
COSC 3P40 – Advanced Object-Oriented Programming
Inheritance for Limitation
Ch.8.4, Budd: Understanding Object-Oriented Programming with Java
class Set extends LinkedList {
// methods addElement, removeElement, contains,
// isEmpty and size are all inherited from LinkedList
public int indexOf(Object obj) {
System.out.println(“Do not use Set.indexOf”);
return 0;
}
public Object elementAt(int index) {
return null;
}
}
© M. Winter
1.19
COSC 3P40 – Advanced Object-Oriented Programming
Inheritance for Combination
public class Mouse extends Vegetarian implements Food {
…
protected RealAnimal getChild() {
…
}
…
public int getFoodAmount() {
…
}
…
}
© M. Winter
1.20
COSC 3P40 – Advanced Object-Oriented Programming
UML Class diagrams
Vehicle
<<interface>>
- speed : Integer
Cloneable
+ Vehicle(speed : Integer)
+ getSpeed() : Integer {leaf}
+ clone() : Object
+ accelerate()
MyCar
1
{leaf}
Truck
0..*
# trailer : Trailer
+ Truck(speed : Integer, tr : Trailer)
+ MyCar(speed : Int)
+ accelerate()
1
Trailer
+ CAPACITY : Integer {readonly}
+ Trailer()
+ clone() : Object
© M. Winter
1.21
COSC 3P40 – Advanced Object-Oriented Programming
Composition
• Composition  has-a relationship (strong ownership)
• Inheritance  is-a relationship
• Inheritance versus composition
– desire to reuse existing implementation
– substitutability (subtype)
– subclass inherits specification and all methods and variables
– composition allows selective reuse
© M. Winter
1.22
COSC 3P40 – Advanced Object-Oriented Programming
UML Class diagrams
Inheritance versus Composition
LinkedList
+ addElement(obj : Object)
+ removeElement(obj : Object)
+ contains(obj : Object) : boolean
+ isEmpty() : boolean
+ size() : int
+ indexOf(obj : Object) : int
+ elementAt(index : int) : Object
public int indexOf(Object obj) {
System.out.println(“Do not use Set.indexOf”);
return 0;
}
Set
public Object elementAt(int index) {
System.out.println(“Do not use Set.elementAt”);
+ indexOf(obj : Object) : int
+ elementAt(index : int) : Object
© M. Winter
return null;
}
1.23
COSC 3P40 – Advanced Object-Oriented Programming
UML Class diagrams
Inheritance versus Composition
LinkedList
1
0..1
Set
- content : LinkedList
+ addElement(obj : Object)
+ addElement(obj : Object)
+ removeElement(obj : Object)
+ removeElement(obj : Object)
+ contains(obj : Object) : boolean
+ contains(obj : Object) : boolean
+ isEmpty() : boolean
+ isEmpty() : boolean
+ size() : int
+ size() : int
+ indexOf(obj : Object) : int
+ elementAt(index : int) : Object
public void addElement(Object obj) {
content.addElement(obj);
}
…
public int size(){
return content.size();
}
© M. Winter
1.24
COSC 3P40 – Advanced Object-Oriented Programming
Generics
• Up to Java 1.4
– container classes store object of class Object
– storing elements in a container uses subtype polymorphism
– accessing elements in a container requires type casting
Stack s = new Stack();
s.push(new Integer(3));
Integer n = (Integer) s.pop();
s.push(”abc”);
Integer second = (Integer) s.pop();
© M. Winter
// cast required
// no error
// runtime error
// (ClassCastException)
1.25
COSC 3P40 – Advanced Object-Oriented Programming
Generics (cont’d)
• from Java 1.5
– generic classes (similar to templates in C++)
Stack<Integer> s = new Stack<Integer>();
s.push(new Integer(3));
Integer n = s.pop();
// no cast required
s.push(”abc”);
// type error
// (at compile time)
© M. Winter
1.26
COSC 3P40 – Advanced Object-Oriented Programming
Generic (cont’d)
Advantages of generics :
• Strong static type-checking
– fewer ClassCastExceptions
– fewer casts
– no unchecked warnings
• Improved readability
• Better tool support
• No future deprecation
© M. Winter
1.27
COSC 3P40 – Advanced Object-Oriented Programming
Generics - UML class diagram
A class generic in E
An instantiation of the
generic class using the
class MyClass1.
Two short forms for an
instantiation (useful if
generic class is not part
of the diagram.
© M. Winter
MyGenericClass
E
<<bind>> E  MyClass1
MyInstantiationClass
MyGenericClass<E  MyClass2>
or
MyGenericClass<MyClass2>
1.28
COSC 3P40 – Advanced Object-Oriented Programming
Generics - Example
public class Pair<X,Y> {
private X first;
private Y second;
// first component of type X
// second component of type Y
public <A extends X,B extends Y> Pair(A a,B b) {
first = a;
second = b;
} // constructor
public Pair(Pair<? extends X, ? extends Y> p) {
first = p.getFirst();
second = p.getSecond();
} // constructor
© M. Winter
1.29
COSC 3P40 – Advanced Object-Oriented Programming
Generics – Example (cont’d)
public X getFirst() {
return first;
} // getFirst
public Y getSecond() {
return second;
} // getSecond
public void setFirst(X x) {
first = x;
} // setFirst
public void setSecond(Y y) {
second = y;
} // setSecond
public boolean equals(Object obj) {
if (obj instanceof Pair<?,?>) {
Pair<?,?> p = (Pair<?,?>) obj;
return first == p.getFirst() && second == p.getSecond();
};
return false;
} // equals
© M. Winter
1.30
COSC 3P40 – Advanced Object-Oriented Programming
Auto boxing
• in Java 1.4
Stack s = new Stack();
s.push(new Integer(3));
// wrapper class needed
Integer n = (Integer) s.pop();
• from Java 1.5
Stack<Integer> s = new Stack<Integer>();
s.push(3);
// auto boxing
int n = s.pop();
// again auto boxing
s.push(new Integer(1));
// without boxing
Integer num = s.pop();
// again without boxing
s.push(2);
// any combination
num = s.pop();
// possible
© M. Winter
1.31
COSC 3P40 – Advanced Object-Oriented Programming
Iterations
• in Java 1.4
List strings;
...
for(int i = 0; i < strings.size(); i++) {
String str = strings.elementAt(i);
System.out.println(str);
}
or better using an iterator
for(Iterator iter = strings.iterator(); iter.hasNext();) {
String str = (String) iter.next();
System.out.println(str);
}
© M. Winter
1.32
COSC 3P40 – Advanced Object-Oriented Programming
Iterations (cont’d)
• from Java 1.5
List<String> strings;
...
for(String str : strings) System.out.println(str);
int[] vector = new int[100];
...
int sum = 0;
for(int elem : vector) sum += elem;
© M. Winter
1.33
COSC 3P40 – Advanced Object-Oriented Programming
Enumeration types
• in Java 1.4
– enumeration types are implemented by using the type int
public static final int RED
= 0;
public static final int YELLOW = 1;
public static final int BLUE
= 2;
...
switch(myColor) {
case Color.RED:
System.out.println(”red”); break;
case Color.YELLOW: System.out.println(”yellow”); break;
case Color.BLUE:
System.out.println(”blue”); break;
};
© M. Winter
1.34
COSC 3P40 – Advanced Object-Oriented Programming
Enumeration types (cont’d)
Advantages of explicit enumeration types:
• they are type safe (checked at compile time)
– int enums don't provide any type safety at all
• they provide a proper name space for the enumerated type
– with int enums you have to prefix the constants to get any semblance of a
name space
• they are robust
– int enums are compiled into clients, and you have to recompile clients if
you add, remove, or reorder constants
• printed values are informative
– if you print an int enum you just see a number
• can be stored in collections (objects)
• arbitrary fields and methods can be added
© M. Winter
1.35
COSC 3P40 – Advanced Object-Oriented Programming
Enumeration types (cont’d)
Simple example:
public enum Color {RED, YELLOW, BLUE};
...
for (Color myColor : Color.values())
System.out.println(myColor);
values() is a static method of an enumeration type returning an array
containing all the values of the enum type in the order they are declared.
© M. Winter
1.36
COSC 3P40 – Advanced Object-Oriented Programming
public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7),
PLUTO (1.27e+22, 1.137e6);
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double mass() { return mass; }
public double radius() { return radius; }
// universal gravitational constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
public double surfaceGravity() { return G * mass / (radius * radius); }
public double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity(); }
}
© M. Winter
1.37
COSC 3P40 – Advanced Object-Oriented Programming
public enum Operation {
PLUS { double eval(double x, double y) { return x + y; } },
MINUS { double eval(double x, double y) { return x - y; } },
TIMES { double eval(double x, double y) { return x * y; } },
DIVIDE { double eval(double x, double y) { return x / y; }};
// Do arithmetic op represented by this constant abstract
double eval(double x, double y);
}
public static void main(String args[]) {
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
for (Operation op : Operation.values())
System.out.printf("%f%s%f=%f%n",x,op,y,op.eval(x,y));
}
© M. Winter
1.38
COSC 3P40 – Advanced Object-Oriented Programming
Enum types - UML class diagram
<<enumeration>>
Planet
MERCURY
VENUS
EARTH
MARS
JUPITER
SATURN
URANUS
NEPTUNE
PLUTO
+ G : double { readonly }
+
+
+
+
© M. Winter
mass() : double
radius() : double
surfaceGravity() : double
surfaceWeight(double) : double
1.39
COSC 3P40 – Advanced Object-Oriented Programming
Static import
Static import
• in Java 1.4
double sinus = Math.sin(Math.PI/2.0);
• from Java 1.5
import static java.lang.Math.*;
double sinus = sin(PI/2.0);
• import of all static components of a class
• usage without class prefix
• different from
import java.util.*;
© M. Winter
1.40
COSC 3P40 – Advanced Object-Oriented Programming
Class Object
• Common parent (base class)
• Minimal functionality
• Classes may override to provide specific behaviour
– public boolean equals(Object other) {…}
– public int hashCode() {…}
– public String toString() {…}
– public Class getClass() {…}
– public Object clone() {…}
© M. Winter
1.41
COSC 3P40 – Advanced Object-Oriented Programming
Serialization
• Serialization is the process of transforming an object into a stream of
bytes.
• Deserialization is the reverse process.
public interface Serializable {};
• Making an object serializable requires almost no effort (the interface
Serializable is empty).
• More complex operations may be necessary if, for instance, just a
portion of an object’s state is to be saved on the output stream.
© M. Winter
1.42
COSC 3P40 – Advanced Object-Oriented Programming
Serialization (cont.)
import java.io.*;
public class IntPair implements Serializable {
int x;
int y;
public IntPair(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return “(" + x + "," + y + ")";
}
}
© M. Winter
1.43
COSC 3P40 – Advanced Object-Oriented Programming
Serialization (cont.)
import java.io.*;
public class inout {
public static void main(String[] args) {
IntPair p = new IntPair(2,3);
try {
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(Filename));
out.writeObject(p);
out.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
© M. Winter
1.44
COSC 3P40 – Advanced Object-Oriented Programming
Serialization (cont.)
import java.io.*;
public class inout {
public static void main(String[] args) {
try {
ObjectInputStream in = new ObjectInputStream(
new FileInputStream(Filename));
IntPair p = (IntPair) in.readObject();
System.out.println(p);
} catch(Exception e) {
e.printStackTrace();
}
}
}
© M. Winter
1.45
COSC 3P40 – Advanced Object-Oriented Programming
Some useful interfaces
• interface Serializable {}
• interface Cloneable {}
– this interface does not include the clone method.
– a class implements the Cloneable interface to indicate to the
Object.clone() method that it is legal for that method to make
a field-for-field copy of instances of that class.
• interface Comparable<T> {
public int compareTo(T o)
}
– this interface imposes a total ordering on the objects of each class
that implements it.
– compareTo(T o) returns a negative integer, zero, or a positive
integer as this object is less than, equal to, or greater than the
specified object.
• interface Comparator<T> {
public int compare(T o1, T o2)
}
© M. Winter
1.46
COSC 3P40 – Advanced Object-Oriented Programming
Utility Classes
The Java library provides a number of small utility classes, including:
• Point
• Dimension
• Date, Calendar
• Math
• Random
• Toolkit
• System
• String and related classes
© M. Winter
1.47
COSC 3P40 – Advanced Object-Oriented Programming
Points
Points represent locations in
a two-dimensional space.
x
y
class Point implements Cloneable, Serializable {
public Point(int x, int y)
//constructor
public int x
public int y
//public accessible data
//fields
public
public
public
public
//move to a given location
//change by offset
//compare two points
//convert to string
void move(int x, int y)
void translate(int x, int y)
boolean equals(Object p)
String toString()
}
© M. Winter
1.48
COSC 3P40 – Advanced Object-Oriented Programming
Dimension
A dimension is used to represent a rectangular size. Dimensions are
characterized by a width and a height.
class Dimension implements Cloneable, Serializable {
public Dimension()
//constructors
public Dimension(int w, int h)
public Dimension(Dimension d) //make a copy (clone ?!?!)
public int width
public int height
//public accessible data fields
public String toString()
//operations
}
© M. Winter
1.49
COSC 3P40 – Advanced Object-Oriented Programming
Date, Calendar
The class Date is used to represent both data and time values.
class Date implements Cloneable, Comparable, Serializable {
public Date()
//constructors
public Date(int year, int month, int day)
//deprecated,
public Date(int year, int month, int day,
//replaced by
int hours, int minutes)
//Calendar and
public Date(int year, int month, int day,
//the set method
int hours, int minutes, int seconds)
public
public
public
public
public
public
public
public
© M. Winter
int
int
int
int
int
int
int
int
getDate()
//field access methods
getDay()
//deprecated, replaced by Calendar and the
getHours()
//get method
getMinutes()
getMonth()
getSeconds()
getYear()
getTimezoneOffset()
1.50
COSC 3P40 – Advanced Object-Oriented Programming
//epoch methods
public long getTime()
//returns milliseconds since epoch
public void setTime(long lval) //set time from epoch
//field setting methods
public void setDate(int date) //deprecated, replaced by
public void setHours(int hour) //Calendar and the get method
public void setMinutes(int minutes)
public void setMonth(int month)
public void setSeconds(int seconds)
public void setYear(int year)
//comparison methods
public boolean after(Date when)
public boolean before(Date when)
public boolean equals(Object when)
//output
public String toString()
}
© M. Winter
1.51
COSC 3P40 – Advanced Object-Oriented Programming
Date - Example
Date start = new Date();
int j = 0;
for (int i = 0; i < 100000; i++)
j = j + 1;
Date end = new Date();
System.out.println(“That took “ +
(end.getTime() – start.getTime()) +
“ milliseconds. “);
© M. Winter
1.52
COSC 3P40 – Advanced Object-Oriented Programming
Math
The class Math provides a number of constants, as well as useful
mathematical functions.
final class Math {
//constants
public static final double E
public static final double PI
//2.71828…
//3.14159…
//trigonometric operations, angles in radians
public static double sin(double num)
public static double cos(double num)
public static double tan(double num)
public static double asin(double num)
public static double acos(double num)
public static double atan(double num)
public static double atan(double s, double c)
© M. Winter
1.53
COSC 3P40 – Advanced Object-Oriented Programming
//rounding operations
public static double ceil(double num)
public static double floor(double num)
public static double rint(double num)
public static int round(float num)
public static long round(double num)
//exponential and powers
public static double
public static double
public static double
public static double
© M. Winter
exp(double y)
pow(double x, double y)
log(double x)
sqrt(double x)
1.54
COSC 3P40 – Advanced Object-Oriented Programming
//other operations
public static int abs(int num)
public static long abs(long num)
public static float abs(float num)
public static double abs(double num)
public static int max(int x, int y)
public static long max(long x, long y)
public static float max(float x, float y)
public static double max(double x, double y)
public static int min(int x, int y)
public static long min(long x, long y)
public static float min(float x, float y)
public static double min(double x, double y)
public static double random()
}
© M. Winter
1.55
COSC 3P40 – Advanced Object-Oriented Programming
Random
The class Random provides more general facilities for random numbers.
class Random implements Serializable {
//constructors
Random()
Random(long seed)
//operations
public void setSeed(long seed)
public double nextDouble()
public float nextFloat()
public int nextInt()
public int nextInt(int n)
public long nextLong()
//alternative distribution
public double nextGaussian()
}
© M. Winter
1.56
COSC 3P40 – Advanced Object-Oriented Programming
Random - Example
static public int weightedDistribution(int[] weights) {
int sum = 0;
for(int i = 0; i < weights.length; i++)
sum += weights[i];
int val = (int) Math.floor(Math.random()*sum + 1);
for(int i = 0; i < weights.length; i++) {
val -= weights[i];
if (val < 0) return i;
}
return 0;
}
© M. Winter
1.57
COSC 3P40 – Advanced Object-Oriented Programming
Toolkit
• This class is the abstract superclass of all actual implementations of the
Abstract Window Toolkit (AWT).
• Useful methods:
– getFontList(): returns an array of string values, containing the
names of the fonts available on the current system.
– getImage(): takes as a parameter either a string (a file name) or a
URL; returns an image as a value of type Image.
– getScreenSize(): returns the number of pixels (type
Dimension) in the screen.
– getScreenResolution(): returns the number of dots per inch.
• The Toolkit class is an example of the Abstract Factory design
pattern .
© M. Winter
1.58
COSC 3P40 – Advanced Object-Oriented Programming
System
• The class System gives access to several system-wide resources.
– System.in: standard input
– System.out: standard output
– System.err: error output
• Useful methods:
– exit(int): immediately halts the current running program,
yielding to the operating system the integer status given in the
argument.
– currentTimeMillis(): returns the current time in milliseconds
since epoch.
© M. Winter
1.59
COSC 3P40 – Advanced Object-Oriented Programming
String
•
•
•
•
In Java a string is an immutable object; it cannot be changed.
implements CharSequence, Comparable, Serializable
String name = “John Smith“;
The addition operator, +, is overloaded:
System.out.println(“The answer is: “ + answer);
– addition operator groups left to right, i.e.,
System.out.println(“Catch-“ + 2 + 2);
yields Catch-22,
System.out.println(2 + 2 + “warned“);
yields 4warned
• use equals(Object obj) or equalsIgnoreCase(String str)
to compare strings
© M. Winter
1.60
COSC 3P40 – Advanced Object-Oriented Programming
String (cont.)
final class String {
public static String valueOf(Object obj) {
if (obj == null)
return “null“;
else
return obj.toString();
}
}
If obj is a string valueOf returns a reference to the original, not a copy!
© M. Winter
1.61
COSC 3P40 – Advanced Object-Oriented Programming
StringBuffer
• String as an array of character symbol; similar to C.
• The methods append, insert, and reverse change the current
string buffer and return a reference to the updated string buffer.
String str1 = “Hello “;
String str2 = str1 + str1;
StringBuffer strbuf1 = new StringBuffer(“Hello “);
StringBuffer strbuf2 = strbuf1.append(strbuf1);
© M. Winter
1.62
COSC 3P40 – Advanced Object-Oriented Programming
Collections
•
•
containers, data structures
kinds
– bags (multiset)
• unordered with duplicates
• Collection
– set
• unordered without duplicates
• also sorted or ordered sets
• Set and SortedSet
– list (sequence)
• ordered with duplicates
• indexing by position
• List
– map (dictionary, associative array)
• unordered (key,value) pairs
– no duplicate keys
– map from key to value
• also sorted or ordered map (by key)
• Map and SortedMap
© M. Winter
1.63
COSC 3P40 – Advanced Object-Oriented Programming
Interfaces
• design guideline – Maximize the Uniformity of Common Aspects of
Related Classes/Interfaces
Iterable
E
Collection
Set
E
E
Map
List
E
K,V
SortedMap
K,V
E
SortedSet
© M. Winter
1.64
COSC 3P40 – Advanced Object-Oriented Programming
Interfaces
•
•
•
•
•
Iterable
– iterator
Collection
– common interface for non-map collections
– equals
Set
– modifies semantics – no duplicates
– SortedSet
List
– modified semantics – ordered
Map
– not Collection – involves keys, no duplicate keys
– views
• entry set (key-value pairs)
• key set
• value collection
– keys
• equals
– SortedMap
© M. Winter
1.65
COSC 3P40 – Advanced Object-Oriented Programming
Collection<E> interface
add(o)
Adds an element o to this collection.
addAll(c)
Adds all the elements in the collection c to this
collection.
clear()
Removes all elements from this collection.
contains(o)
Returns true if this collection contains an element that
equals o.
containsAll(c) Returns true if this collection contains all the elements
in the collection c.
isEmpty()
Returns true if this collection contains no elements.
iterator()
Returns an Iterator over the elements in this
collection.
remove(o)
Removes an element that equals o from this collection.
removeAll(c)
Removes from this collection all elements from c.
retainAll(c)
Retains only the elements that are contained in c.
size()
Returns the number of elements in this collection.
© M. Winter
1.66
COSC 3P40 – Advanced Object-Oriented Programming
Set<E> interface
add(o)
Adds an element o to this set if it is not already present.
addAll(c)
Adds all the elements in the collection c to this set if
they are not already present.
© M. Winter
1.67
COSC 3P40 – Advanced Object-Oriented Programming
List<E> interface
add(i, o)
Insert the element o at the i-th position in this list.
add(o)
Appends the element o to the end of this list.
addAll(c)
Inserts all the elements in the collection c to the end of
this list, in the order that they are returned by the
iterator of c.
addAll(i, c)
Inserts all the elements in the collection c into this list,
starting at the i-th position.
get(i)
Returns the element at the i-th position in this list.
indexOf(o)
Returns the index in this list of the first occurrence of
the element o, or –1 if the element is not present in this
list.
lastIndexOf(o)
Returns the index in this list of the last occurrence of
the element o, or –1 if the element is not present in this
list.
listIterator()
Returns a ListIterator of the elements of this list.
© M. Winter
1.68
COSC 3P40 – Advanced Object-Oriented Programming
List<E> interface (cont.)
listIterator(i)
Returns a ListIterator of the elements of this list,
starting from the i-th position.
remove(i)
Removes the element at the i-th position in this list
and returns the removed element.
remove(o)
Removes the first occurrence of the element o from this
list.
set(i, o)
Replaces the element at the i-th position in this list
with the element o, and returns the element that was
replaced.
subList(i, j)
Returns a sublist of this list from the i-th position,
inclusive, to the j-th position, exclusive.
© M. Winter
1.69
COSC 3P40 – Advanced Object-Oriented Programming
SortedSet<E> interface
comparator()
Returns the comparator associated with this sorted set,
or null if the natural order is used.
first()
Returns the first (lowest) element currently in this sorted
set.
headSet(o)
Returns a set view of the portion of this sorted set whose
elements are strictly less than o.
last()
Returns the last (highest) element currently in this
sorted set.
subSet(o1, o2) Returns a set view of the portion of this sorted set whose
elements range from o1, inclusive, to o2, exclusive.
tailSet(o)
© M. Winter
Returns a set view of the portion of this sorted set whose
elements are greater than or equal to o.
1.70
COSC 3P40 – Advanced Object-Oriented Programming
Map<K,V> interface
clear()
Removes all entries from this map.
containsKey(k)
Returns true if this map contains an entry for the key
k.
containsValue(v)
Returns true if this map contains one or more entries
with the value v.
entrySet()
Returns the entry view of this map.
get(k)
Returns the value to which maps this map the key k.
isEmpty()
Returns true if this map contains no entries.
keySet()
Returns the key set view of this map.
put(k, v)
Maps the key k to the value v in this map.
putAll(m)
Copies all entries from the map m to this map.
remove(k)
Removes the entry for key k from this map if present.
size()
Returns the number of entries in this map.
values()
Returns the value collection view of this map.
© M. Winter
1.71
COSC 3P40 – Advanced Object-Oriented Programming
SortedMap<K,V> interface
comparator()
Returns the comparator associated with this sorted map,
or null if the natural order is used.
firstKey()
Returns the first (lowest) key currently in this sorted
map.
headMap(k)
Returns a map view of the portion of this sorted map
whose keys are strictly less than k.
lastKey()
Returns the last (highest) key currently in this sorted
map.
subMap(k1, k2) Returns a map view of the portion of this sorted map
whose keys range from k1, inclusive, to k2, exclusive.
tailMap(k)
© M. Winter
Returns a map view of the portion of this sorted map
whose keys are greater than or equal to k.
1.72
COSC 3P40 – Advanced Object-Oriented Programming
Concrete Classes
Important issues:
• bounded versus unbounded
• time and space complexity of various operations
• interchangeability
• concrete collection classes in Java
– all unbounded
© M. Winter
1.73
COSC 3P40 – Advanced Object-Oriented Programming
Set<E>
• HashSet<E>
– hash table (efficient in insertion and membership checking)
– unpredictable iteration order
– requires equals and hashCode
• LinkedHashSet<E> (similar to HashSet)
– hash table with linked elements
– predictable iteration order (usually insertion order)
– requires equals and hashCode
• TreeSet<E>
– red-black tree (a form of balanced binary trees)
– SortedSet
– requires ordering (Comparable or Comparator)
– iteration by natural order
– less efficient in insertion and membership checking
 Use HashSet unless a sorted set or a predictable iteration order
is required.
© M. Winter
1.74
COSC 3P40 – Advanced Object-Oriented Programming
List<E>
• ArrayList<E>
– array extended when necessary
– large enough to hold predicted number of elements
– often, a large portion of the array is unused
– large cost to increase size (copying)
– more efficient access
• Vector<E>
– same implementation as the ArrayList
– supports additional “legacy methods”
– thread-safe
– significant overhead in performance
• LinkedList<E>
– doubly-linked list
– no additional penalty as list grows
– less efficient access
 LinkedList for volatile lists, ArrayList for stable lists
© M. Winter
1.75
COSC 3P40 – Advanced Object-Oriented Programming
Map<K,V>
• HashMap<K,V>
– hash table (efficient in insertion and membership checking)
– unpredictable iteration order
– requires equals and hashCode
• Hashtable<K,V>
– same implementation as the HashMap
– supports additional “legacy methods”
– thread-safe
– significant overhead in performance
• LinkedHashMap<K,V>
– hash table with linked elements
– predictable iteration order (usually insertion order)
– requires equals and hashCode
© M. Winter
1.76
COSC 3P40 – Advanced Object-Oriented Programming
• IdentityHashMap<K,V> (similar to HashMap)
– key equality based on == (identity)
– requires hashCode
• TreeMap<K,V>
– red-black tree
– SortedMap
– iteration order by key
– requires ordering for keys (Comparable or Comparator)
– less efficient in insertion and membership checking
 Use TreeMap if a sorted map is required otherwise use HashMap or
IdentityHashMap.
© M. Winter
1.77
COSC 3P40 – Advanced Object-Oriented Programming
Abstract Collection Classes
•
•
•
•
•
•
for building new collections
AbstractCollection<E>
– bag
– must implement iterator and size
AbstractSet<E>
– must implement add
AbstractList<E>
– optimized for random access
– must implement get and size
AbstractSequentialList<E>
– optimized for sequential access
– must implement listIterator and size
AbstractMap<K,V>
– must implement entries
© M. Winter
1.78
Download