Presentation is loading. Please wait.

Presentation is loading. Please wait.

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1.11.1 COSC 3P91 Advanced Object-Oriented Programming Super Course Instructor: Michael Winter.

Similar presentations


Presentation on theme: "© M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1.11.1 COSC 3P91 Advanced Object-Oriented Programming Super Course Instructor: Michael Winter."— Presentation transcript:

1 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1.11.1 COSC 3P91 Advanced Object-Oriented Programming Super Course Instructor: Michael Winter –Office J323 –email: mwinter@brocku.ca Webpage: www.cosc.brocku.ca/~mwinter/Courses/3P91

2 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1.21.2 Course Description (Brock Calendar): Advanced object-oriented programming techniques such as graphical user interfaces, animation, sound, music, networking, parallelism, client- server and XML using game design as an example. Topics in object- oriented 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

3 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1.31.3 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

4 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1.41.4 Course Work Marking Scheme –Project = 4 Programming parts 60% (done in class/lab, 4x15%) –Final Exam 40% (Saturday May 09, 09:00am - 11:00am, TH246) Programming parts 1-4 due by the end of each day (05:00pm) starting on Tuesday, May 06.

5 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1.51.5 Course Outline DayDateBook/Chapt.Topics 1May 04[2]/4,5,6.7,8Introduction, review of OO concepts, basic UML, Utility classes, collection classes 2May 05[2]/7,8I/O, Design patterns 3May 06[1]/1,[2]/7,8, 11 XML, Threads, multitasking, Concurrency design patterns 4May 07[1]/2,[2]/8GUI (AWT, Swing), 2D graphics, animation 5May 08[1]/3,4,6Sound effects & music, Network programming

6 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1.61.6 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

7 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1.71.7 Classes [ClassModifiers] class ClassName [extends SuperClass] [implements Interface 1, Interface 2, …] { ClassMemberDeclarations } Class modifiers –visibility: package versus public –abstract –final extends clause specifies the superclass implements clause specifies the interfaces being implemented

8 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1.81.8 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)

9 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1.91.9 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)

10 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 10 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 T 1 is a subtype of type T 2 if every legitimate value of T 1 is also a legitimate value of T 2. In this case, T 2 is a supertype of T 1. Substitutability of subtypes: A value of a subtype can appear wherever a value of its supertype is expected.

11 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 11 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

12 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 12 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

13 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 13 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

14 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 14 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 }

15 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 15 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(); } }

16 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 16 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) {…} }

17 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 17 Inheritance for Specialization public class MyCar extends Car { … public void startEngine() { motivateCar(); super.startEngine(); } … }

18 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 18 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); } }

19 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 19 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; }

20 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 20 Inheritance for Combination public class Mouse extends Vegetarian implements Food { … protected RealAnimal getChild() { … } … public int getFoodAmount() { … } … }

21 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 21 UML Class diagrams Vehicle - speed : Integer + Vehicle(speed : Integer) + getSpeed() : Integer {leaf} + accelerate() MyCar {leaf} + MyCar(speed : Int) + accelerate() 1 Truck # trailer : Trailer + Truck(speed : Integer, tr : Trailer) > Cloneable + clone() : Object Trailer + CAPACITY : Integer {readonly} + Trailer() + clone() : Object 0..* 1

22 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 22 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

23 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 23 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 Set + indexOf(obj : Object) : int + elementAt(index : int) : Object public int indexOf(Object obj) { System.out.println(“Do not use Set.indexOf”); return 0; } public Object elementAt(int index) { System.out.println(“Do not use Set.elementAt”); return null; }

24 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 24 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 Set - content : LinkedList + addElement(obj : Object) + removeElement(obj : Object) + contains(obj : Object) : boolean + isEmpty() : boolean + size() : int public void addElement(Object obj) { content.addElement(obj); } … public int size(){ return content.size(); } 1 0..1

25 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 25 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();// cast required s.push(”abc”);// no error Integer second = (Integer) s.pop();// runtime error // (ClassCastException)

26 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 26 Generics (cont’d) from Java 1.5 –generic classes (similar to templates in C++) Stack s = new Stack (); s.push(new Integer(3)); Integer n = s.pop();// no cast required s.push(”abc”);// type error // (at compile time)

27 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 27 Generic (cont’d) Advantages of generics : Strong static type-checking –fewer ClassCastException s –fewer casts –no unchecked warnings Improved readability Better tool support No future deprecation

28 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 28 Generics - UML class diagram MyGenericClass E MyInstantiationClass > E  MyClass1 MyGenericClass 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. MyGenericClass or

29 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 29 Generics - Example public class Pair { private X first;// first component of type X private Y second;// second component of type Y public Pair(A a,B b) { first = a; second = b; } // constructor public Pair(Pair p) { first = p.getFirst(); second = p.getSecond(); } // constructor

30 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 30 Generics – Example (cont’d) public X getFirst() { return first; } // getFirst public void setFirst(X x) { first = x; } // setFirst public Y getSecond() { return second; } // getSecond 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

31 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 31 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 s = new Stack (); 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

32 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 32 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); }

33 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 33 Iterations (cont’d) from Java 1.5 List strings;... for(String str : strings) System.out.println(str); int[] vector = new int[100];... int sum = 0; for(int elem : vector) sum += elem;

34 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 34 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; };

35 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 35 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

36 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 36 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.

37 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 37 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(); } }

38 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 38 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)); }

39 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 39 Enum types - UML class diagram > Planet MERCURY VENUS EARTH MARS JUPITER SATURN URANUS NEPTUNE PLUTO + G : double { readonly } + mass() : double + radius() : double + surfaceGravity() : double + surfaceWeight(double) : double

40 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 40 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.*;

41 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 41 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() {…}

42 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 42 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.

43 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 43 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 + ")"; }

44 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 44 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(); }

45 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 45 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(); }

46 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 46 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 { 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 { public int compare(T o1, T o2) }

47 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 47 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

48 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 48 Points class Point implements Cloneable, Serializable { public Point(int x, int y)// constructor public int x// public accessible data public int y// fields public void move(int x, int y)// move to a given location public void translate(int x, int y)// change by offset public boolean equals(Object p)// compare two points public String toString()// convert to string } x y Points represent locations in a two-dimensional space.

49 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 49 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 accessible data fields public int height public String toString() // operations }

50 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 50 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 int getDate()// field access methods public int getDay()// deprecated, replaced by Calendar and the public int getHours()//get method public int getMinutes() public int getMonth() public int getSeconds() public int getYear() public int getTimezoneOffset()

51 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 51 // 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() }

52 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 52 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. “);

53 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 53 Math The class Math provides a number of constants, as well as useful mathematical functions. final class Math { // constants public static final double E//2.71828… public static final double PI//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)

54 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 54 // 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 exp(double y) public static double pow(double x, double y) public static double log(double x) public static double sqrt(double x)

55 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 55 // 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() }

56 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 56 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() }

57 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 57 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; }

58 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 58 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.

59 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 59 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.

60 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 60 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

61 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 61 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!

62 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 62 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);

63 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 63 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

64 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 64 Interfaces design guideline – Maximize the Uniformity of Common Aspects of Related Classes/Interfaces Collection Set SortedSet List Map SortedMap E EE E Iterable E K,V

65 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 65 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

66 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 66 Collection 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.

67 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 67 Set 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.

68 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 68 List 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.

69 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 69 List 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.

70 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 70 SortedSet 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) Returns a set view of the portion of this sorted set whose elements are greater than or equal to o.

71 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 71 Map 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.

72 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 72 SortedMap 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) Returns a map view of the portion of this sorted map whose keys are greater than or equal to k.

73 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 73 Concrete Classes Important issues: bounded versus unbounded time and space complexity of various operations interchangeability concrete collection classes in Java –all unbounded

74 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 74 Set HashSet –hash table (efficient in insertion and membership checking) –unpredictable iteration order –requires equals and hashCode LinkedHashSet (similar to HashSet ) –hash table with linked elements –predictable iteration order (usually insertion order) –requires equals and hashCode TreeSet –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.

75 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 75 List ArrayList –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 –same implementation as the ArrayList –supports additional “legacy methods” –thread-safe –significant overhead in performance LinkedList –doubly-linked list –no additional penalty as list grows –less efficient access  LinkedList for volatile lists, ArrayList for stable lists

76 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 76 Map HashMap –hash table (efficient in insertion and membership checking) –unpredictable iteration order –requires equals and hashCode Hashtable –same implementation as the HashMap –supports additional “legacy methods” –thread-safe –significant overhead in performance LinkedHashMap –hash table with linked elements –predictable iteration order (usually insertion order) –requires equals and hashCode

77 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 77 IdentityHashMap (similar to HashMap ) –key equality based on == (identity) –requires hashCode TreeMap –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.

78 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1. 78 Abstract Collection Classes for building new collections AbstractCollection –bag –must implement iterator and size AbstractSet –must implement add AbstractList –optimized for random access –must implement get and size AbstractSequentialList –optimized for sequential access –must implement listIterator and size AbstractMap –must implement entries


Download ppt "© M. Winter COSC 3P91 – Advanced Object-Oriented Programming 1.11.1 COSC 3P91 Advanced Object-Oriented Programming Super Course Instructor: Michael Winter."

Similar presentations


Ads by Google