COMP1020_S13_FULL_Review1.pdf - 13-\u00ad\u201008-\u00ad\u201001 COMP 1020 Summer 2013 FULL REVIEW Exam Focus \u2022\u202f Results of building up from Arrays and Objects to

COMP1020_S13_FULL_Review1.pdf -...

This preview shows page 1 out of 30 pages.

You've reached the end of your free preview.

Want to read all 30 pages?

Unformatted text preview: 13-­‐08-­‐01 COMP 1020 Summer 2013 FULL REVIEW Exam Focus •  Results of building up from Arrays and Objects to Object Hierarchy, Linked Lists and MulN Dimensional Arrays robbiemelvin Dept. Comp Sci University of Manitoba 2 1 13-­‐08-­‐01 Exam Focus •  Know the types of SorNng Algorithms –  InserNon, bubble, selecNon, merge, quick –  Which are more efficient as n (size of space) grows and basics of why this is robbiemelvin Dept. Comp Sci University of Manitoba 3 Exam Focus •  WriNng Classes to be used in Object Oriented programs –  Private instance variables –  Constructors –  toString, Equals, compare methods –  Private worker methods, public accessor methods robbiemelvin Dept. Comp Sci University of Manitoba 4 2 13-­‐08-­‐01 Exam Focus •  Write a Class hierarchy and understand how the JVM accesses objects and the various instance methods/variables at run Nme –  Know how to take advantage of the SuperClass so that you can write as li\le code as possible in the SubClasses. –  Protected variables, use of super(), overloading() robbiemelvin Dept. Comp Sci University of Manitoba 5 Exam Focus •  Understand the purpose of try/catch blocks and how excepNons are triggered robbiemelvin Dept. Comp Sci University of Manitoba 6 3 13-­‐08-­‐01 Exam Focus •  Understand what recursion is. Be able to break a problem up into smaller parts of the same type, and idenNfy the base case (where there is no recursive call). robbiemelvin Dept. Comp Sci University of Manitoba 7 Exam Focus •  Be clear on the differences between an array and an ArrayList and write code for the data structure referenced. –  Recall that the indices are adjusted when you remove/add items from an ArrayList –  size() vs length –  use of generics –  [i] vs get(i) robbiemelvin Dept. Comp Sci University of Manitoba 8 4 13-­‐08-­‐01 Exam Focus •  Recall how to walk through a mulN-­‐ dimensional array –  How to instanNate a 2D array, –  how to set values within it, and –  how to access the number of rows and columns of an array of this type. robbiemelvin Dept. Comp Sci University of Manitoba 9 Exam Focus •  Understand the basics of when one algorithm is less efficient for large sizes of n than another. What is happening to the soluNon space (n) in the code. Is the code walking through everything once, twice? Or is the code able to break the space into smaller bits it can handle more efficiently? robbiemelvin Dept. Comp Sci University of Manitoba 10 5 13-­‐08-­‐01 Programming Overview •  Resources –  h\p://wiki1010.cs.umanitoba.ca/mediawiki/ index.php/COMP1010 –  h\p://docs.oracle.com/javase/6/docs/api/ •  Programming Community –  h\p://stackoverflow.com/ robbiemelvin Dept. Comp Sci University of Manitoba 11 Growing Algorithms •  Start with simple methods and Test then ‘grow’ the program in complexity tesNng as you go •  Start off with hard coded inputs to test methods, then add I/O to program •  Keep backups for reverNng updates •  following standards aids in understanding during development and maintenance robbiemelvin Dept. Comp Sci University of Manitoba 12 6 13-­‐08-­‐01 1020 Programming Standards Appropriate variable names an proper capitalizaNon for methods and variables •  Class name InitialCapitalLetters, variables and methods: subsequentLeadingCaps, constants: ALL_CAPS_UNDERSCORE_BREAKS! –  Use indentaNon, make it readable –  No magic numbers •  •  •  sum = 0; Literal constant 0 is OK count = count + 1; Literal constant 1 is OK price = total + 1.07; Magic, not proper. Use named constant like PST_RATE = 1.07; –  Don’t use break (unless in switch statement) and only have ONE return statement per method –  avoid updaNng loop control inside the loop –  Main should be calling other methods and have as li\le naNve programming as possible –  Use formaqng for I/O –  Instance variables should be private unless specifically required to be otherwise, use accessors robbiemelvin Dept. Comp Sci University of Manitoba 13 File IO •  Watch for IDE (integrated development environment) quirks regarding path setup for accessing files •  BufferedReader is one of several libraries available •  Pass file name as a string to FileReader constructor. Pass new fileReader object to BufferedReader constructor… now you have a BufferedReader Object robbiemelvin Dept. Comp Sci University of Manitoba 14 7 13-­‐08-­‐01 File I/O •  File I/O can be encapsulated into a Class to simplify it further or simply a few methods within any class. •  Make sure that file is closed at end of program •  See example FileIO.java robbiemelvin Dept. Comp Sci University of Manitoba 15 File IO – ExcepNons •  Wrap code involving unknown possible errors in a try/catch block try {! //accessing a local or network drive file! //using some periphery IO device that may or may not work! //calling any library that is known to throw exceptions ! } catch(Exception e) {! !//code that handles the error! !System.out.println(e.message);! !e.printStrackTrace();! }! robbiemelvin Dept. Comp Sci University of Manitoba 16 8 13-­‐08-­‐01 Throwing ExcepNons •  Your method may fail and you want to propagate that to the calling method… throw an excepNon: Public void myMethod() throws Exception {! !//do some I/O stuff in here without benefit of a try/catch! Or! !//you can throw a new exception directly! if (sky.equals(“green”)) {! ! !throw new Exception(“Something went horribly wrong!”);! }! }! •  now your method can operate without the try/catch but any method calling it will require the try/catch block, the error will be propagated up to be handled at a higher level. robbiemelvin Dept. Comp Sci University of Manitoba 17 Basic Objects •  Encapsulates data and funcNons related to one topic… abstracts ideas into things •  Building blocks: –  DeclaraNon –  Variables (instance and class) –  Constructor –  Accessors –  Modifiers –  Instance methods –  StaNc Class methods robbiemelvin Dept. Comp Sci University of Manitoba 18 9 13-­‐08-­‐01 Instance vs Class methods •  Instance variables and methods can only be accessed by creaNng an instance of a class… ie an object •  Instance variables and methods deal with an instance of the class (an object), with a specific state which is stored in the instance variables •  Class methods and variables are staNc, they are accessed via the class name itself, the staNc methods generally do not have state, they operate outside any instance of the class and do not have access to instance variables and methods. •  Class methods and variables are oven ‘helper’ methods robbiemelvin Dept. Comp Sci University of Manitoba 19 String ManipulaNon •  Strings are Objects, a Class defined by the Java API •  Imagine a dynamic array of char •  Text pg 127 lists some instance methods for strings. •  Note you cannot compare strings using == you must use myString.equals(compareString) as they are objects, there are mulNple components to a string that must be compared •  Sorts via ascii robbiemelvin Dept. Comp Sci University of Manitoba 20 10 13-­‐08-­‐01 h\ps:// commons.wikimedia.org/ wiki/File:ASCII-­‐Table.svg robbiemelvin Dept. Comp Sci University of Manitoba 21 Object CollecNons •  Arrays –  Problems with arrays –  Really is an object in the end –  System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length ) •  Where src and dest are the source and destination arrays •  ArrayList –  Class type describing an object that is used to store other objects… a data structure. –  Can grow and shrink (the mechanism is hidden from us) –  Be careful when removing items in a loop as the indices change! robbiemelvin Dept. Comp Sci University of Manitoba 22 11 13-­‐08-­‐01 String Formaqng Format Code Meaning %d Format as digit integer (grandfathered in from C) %s Format as string %f Format as float %n Newline 5 Number of spaces provided for the data… will be overriden if data is too big .2 How many decimal points to show, precision aver decimal + Include the sign -­‐ Lev jusNfy , Include grouping in Manitoba number robbiemelvin Dept. Comp Sci University of 23 Data Structures •  Data Structures provide ability to manage collecNons of data types without having to write massive amounts of code –  ArrayList Class solves short comings of Array •  Import java.uNl.* package to access Arraylist class robbiemelvin Dept. Comp Sci University of Manitoba 24 12 13-­‐08-­‐01 ArrayLists •  ArrayList accepts OBJECTS only and expects the Class for the objects in quesNon to have equals() and toString() to be defined •  You must cast objects extracted from an ArrayList to their own Class type before using their type specific instance methods/variables •  We can take advantage of provided methods for relaNvely simplified algorithms for managing content in ArrayList collecNons. robbiemelvin Dept. Comp Sci University of Manitoba 25 Generics •  ArrayList -­‐ can contain ALL types of objects •  We have to cast objects as they are pulled Product p = (Product) list.get(i); •  But we can force the type by declaring this up front ArrayList<Product> inventory = new ArrayList<Product>(); robbiemelvin Dept. Comp Sci University of Manitoba 26 13 13-­‐08-­‐01 Related Topics Wrapper Classes ArrayList<Integer> list = new ArrayList<Integer>(); int sum = 0; for (int i=0;i< list.size();i++) { list.add(i); sum += list.get(i); } Java takes care of puqng ints into and out of Integer objects for us. robbiemelvin Dept. Comp Sci University of Manitoba 27 Related Topics •  OrganizaNon of files aids understanding •  Use of generics simplifies ArrayList object access •  Auto packing and unpacking of primiNves from Wrapper classes •  Test your code on mulNple cases •  Note changes in object indices when using ArrayList robbiemelvin Dept. Comp Sci University of Manitoba 28 14 13-­08-­‐01 Object Hierarchy •  Objects – a quick review •  Object Hierarchy –  What is the relaNonship between a Superclass and a Subclass –  What does UML look like –  The Protected visibility modifier –  InheriNng and Extending •  “Object” is also a Class robbiemelvin Dept. Comp Sci University of Manitoba 29 Class Hierarchy •  Object is THE root Class of ALL Classes •  Any Java Object Hierarchy must be top down, one to many •  Subclasses can access PROTECTED variables and methods of superclass but not vice versa •  Private is private robbiemelvin Dept. Comp Sci University of Manitoba 30 15 13-­‐08-­‐01 Inheritance •  Classes inherit public variables/methods of the hierarchy •  Subclasses EXTEND Superclass by adding variables/methods and by overriding methods •  Subclass describes a more specific object belonging to the same more general superclass robbiemelvin Dept. Comp Sci University of Manitoba 31 Inheritance UML Animal Animal() toString() Cat Cat() Dog Dog() myMethod() myMethod() Bunny Bunny() myMethod() toString() •  The contstructor in the subClasses (Cat, Dog, and Bunny) need to call the super() in order to acNvate the Animal() constructor. •  Objects of the type Cat and Dog will invoke the toString()method from the Animal class as they are in the Animal hierarchy, Objects of the type Bunny will invoke the Bunny toString method since it has been overridden. robbiemelvin Dept. Comp Sci University of Manitoba 32 16 13-­‐08-­‐01 SuperClass -­‐ SubClasses class Animal { protected String name; protected int legs; protected String transport; public Animal() { //defaults; this.name = “unknown”; this.legs = 4; this.transport = “walks; } public String toString() { return this.name; } } class Gecko extends Animal { public Gecko(String name){ //implicit this.name = name; } public String toString() { return this.name + " is a Gecko and he " + this.transport; } } class Dog extends Animal { public Dog() { //implicitly calls super(); } public void setName(String name) { this.name = name; } } class Cat extends Animal { private int attitude; public Cat(int attitude) { super(); //explicitly calling super(); this.attitude = attitude; } } class Bunny extends Animal { public Bunny() { // implicitly calls super // then writes over the transport this.transport = “hops”; } } robbiemelvin Dept. Comp Sci University of Manitoba 33 SorNng •  IteraNve sort methods (but could be done recursively if you chose to – think about that) –  InserNon, selecNon, bubble (next slides) robbiemelvin Dept. Comp Sci University of Manitoba 34 17 13-­‐08-­‐01 Bubble Sort ① UnNl we make a pass without having to swap any items ② Pick the first and second items (this is the bubble) ③ If the second is smaller than the first – swap them ④  make the second item the first item in the bubble ⑤ Pick the next item from the list as the second item in the bubble ⑥ If we are at the end of the list then go back to (1) otherwise go to item (3) robbiemelvin Dept. Comp Sci University of Manitoba 35 Bubble Sort public sta5c void bubbleSort(int numbers){ int temp; //two loops (nested) = n-­‐squared big-­‐O for(int i=0; i<numbers.length; i++) { //only for(int j=0;j<numbers.length-­‐i-­‐1;j++) { //this is the bubble if(numbers[j] > numbers[j+1]) { //swap if needed temp = numbers[j]; numbers[j] = numbers[j+1]; numbers[j+1] = temp; } } } } robbiemelvin Dept. Comp Sci University of Manitoba 36 18 13-­‐08-­‐01 SelecNon Sort ① UnNl each place in the array has accepted the correct item ②  Start with the last place in the array for place ③  n = the first element in the array ④ If the next element is greater than n (largest element we’ve found so far) then set n to this item ⑤ Repeat 4 unNl we get to the place we are working on ⑥ Swap the elements in place and n since n is the largest element ⑦ Move place to one less, ⑧ Repeat from step (3) robbiemelvin Dept. Comp Sci University of Manitoba 37 SelecNon Sort public sta5c void selec5onSort(int numbers){ int largestIndex; int temp; for(int i=1;i<numbers.length-­‐1;i++) { largestIndex = 0; for(int j=1;j<numbers.length-­‐i;j++) { if(numbers[largestIndex] < numbers[j]) { largestIndex = j; } } temp = numbers[numbers.length-­‐1-­‐i]; numbers[numbers.length-­‐1-­‐i] = numbers[largestIndex]; numbers[largestIndex] = temp; } } robbiemelvin Dept. Comp Sci University of Manitoba 38 19 13-­‐08-­‐01 InserNon Sort ①  Create a new list of the same size as the one we are sorNng ②  Put the first element from our list into the first spot in the new list ③  Take the next element from our old list and choose where to put it in the new list a)  b)  c)  d)  Is the new element smaller or larger than the first element in our list. If smaller put before If larger check if smaller or larger than next item, if smaller place before and shiv all aver, else move to next item in new list Repeat from b unNl item has been placed ④  Repeat (3) for each item in the old list ⑤  Return new list (or copy new list into old list) robbiemelvin Dept. Comp Sci University of Manitoba 39 InserNon Sort public sta5c void insertSort(int numbers){ int element; int newList; if(numbers.length >= 1) { newList = new int[numbers.length]; newList[0] = numbers[0]; }else { //no elements in the array newList = new int[0]; } for(int i=1;i<numbers.length;i++) { element = numbers[i]; int j; for( j=i;j>0&& newList[j-­‐1]>element;j-­‐-­‐){ newList[j] = newList[j-­‐1]; } newList[j] = element; } System.arraycopy(newList, 0,numbers, 0,numbers.length); } //without extra array...take from the next spot... //shiv everything over in the sorted parNNon unNl you find where it goes //this is sort of leading up to a quicksort... theres a sorted parNNon and an unsorted parNNon public sta5c void insertSort2(int numbers){ int element; for(int i=1;i<numbers.length;i++) { element = numbers[i]; int j; for( j=i;j>0 && numbers[j-­‐1]>element;j-­‐-­‐){ numbers[j] = numbers[j-­‐1]; } numbers[j] = element; } robbiemelvin Dept. Comp Sci University of Manitoba 40 20 13-­‐08-­‐01 Recursion Key to recursive method is condiNon statements (could be explicit or implicit) that split the method into : -­‐  At LEAST one return case that does not involve a recursive call (this might be a do nothing case) -­‐  At LEAST one recursive case – a self referenNal call with adjusted input. -­‐  A secNon that covers off excepNon cases robbiemelvin Dept. Comp Sci University of Manitoba 41 Recursion – String ManipulaNon •  Can use recursion to do string manipulaNon –  check for palindrome –  Build string values for mulN part data structure –  Reverse the components of a string robbiemelvin Dept. Comp Sci University of Manitoba 42 21 13-­‐08-­‐01 Recursion – String ManipulaNon CODE Palindrome Public staNc Boolean palindrome(String string) { boolean result; if (string.length() <=1) { result = true; } else if (string.charAt(0) != string.charAt(string.elngth() -­‐1){ result = false; }else { result = palindrome(string.substring(1,string.length()-­‐1) } } Run through the code Palindrome(“aabbsccbbaa”) = Palindrome(“abbsccbba”) = Palindrome(“bbsccbb”) = Palindrome(“bsccb”) = Palindrome(“scc”) = Palindrome(“scc”) = false Palindrome(“aaaa”) = Palindrome(“aa”) = Palindrome(“aa”) = Palindrome(“”) =true robbiemelvin Dept. Comp Sci University of Manitoba 43 Recursive Sorts •  Recursive sort methods Split up the space into smaller sort spaces •  Merge sort Splits the space in half, recursively merge sorts the halves, then merge them back together •  Quick sort picks a pivot and splits the space into larger than and smaller than the pivot (in place), then recursively quick sorts the parNNons –  Note that the parNNons may not be exact halves. robbiemelvin Dept. Comp Sci University of Manitoba 44 22 13-­‐08-­‐01 Recursion – fibonacci when recursion is not the best opNon CODE public sta5c int fibR(int num) { int fib; fib = 0; if ((num == 1) || (num == 2)) { fib = 1; } else if (num > 2) { fib = fibR(num -­‐ 1) + fibR(num -­‐ 2); } return fib; } Run through the code fibR(5) =fib(4) + fib(3) =fib(3) + fib(2) + fib(2) + fib(1) = fib(2) + fib(1) + 1 + 1 + 1 = 1 + 1 + 1 + 1 + 1 = 5 fibR(6) = fibR(5) + fibR(4) = fibR(4) + fibR(3) + fibR(3) + fibR(2) = fibR(3)+fibR(2)+fibR(2)+fibR(1) + fibR(2)+fibR(1) + 1 = fibR(2)+fibR(1) + 1 + 1 + 1 + 1 + 1 + 1 = + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 8 fibR(8) = fibR(7) + fibR(6) = fibR(6)+fibR(5) + bibR(5)+fibR(4) = fibR(5) + fibR(4) + fibR(4)+fibR(3) + fibR(4)+fibR(3) + fibR(3)+fibR(2) = fibR(4)+fibR(3)+fibR(3)+fibR(2)+fibR(3)+fibR(2)+fibR(2) + fibR(1) + fibR(3) + fibR(2) + fibR(2) + fibR(1)+ fib(2) + fib(1) + 1 = fibR(3)+fibR(2) + fibR(2) + fibR(1) + fibR(2) + fibR(1)+ 1 + fibR(2) + fib(1) + 1 + 1 + 1 + fibR(2) + fibR(1) + 1 + 1 + 1 + 1 + 1 + 1 = fibR(2) + fibR(1) + 19 = 21 But you see all the duplicate calculaNng! robbiemelvin Dept. Comp Sci University of Manitoba 45 Recursion – Binary Search •  Recursion is useful in any situaNon where you are able to break the problem space up into smaller problems of the same type •  Searching a sorted list is a good example robbiemelvin Dept. Comp Sci University of Manitoba 46 23 13-­‐08-­‐01 Recursion – Binary Search Binary Search Public static int searchList(int list, int search) { Resturn binarySearch(list, search, 0 list.length-­‐1); } public static int binarySearch(int list, int search, int left, int right) { int middle; int result; middle = left + ((right-­‐left)/2); if (left> right) { result = -­‐1; }else if (search == list[middle]) { result = middle; }else if (search < list[middle] { result = binarySearch(list,search,left,middle-­‐1); } else { result = binarySearch(list,search,middle+1,right); } return result; } list = {2,4,6,8,10,24,33,45}; search = 24 binarySearch(list,24,0,7) middle = 7-­‐0/2 = 3 0 < 7 list[middle] = 8 8!=24 24 > 8 so binarySearch(list,24,4,7) middle = 4 + (7-­‐4)/2 = 4 + 1 = 5 list[middle] = list[5] = 24 search = 24 so return middle return 5 robbiemelvin Dept. Comp Sci University of Manitoba 47 Recursion -­‐ Summary •  How can the problem be defined as smaller problems of the same type? •  How can a recursive call reduce the problem to the smaller problem? •  What would the base case of the problem be? The simple answer to the smallest version of the problem. •  Will reducing the problem bring your algorithm to the base case? Cover all situaNons. robbiemelvin Dept. Comp Sci University of Manitoba 48 24 13-­‐08-­‐01 MulN Dimensional Arrays •  An Ar...
View Full Document

  • Fall '15

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture