1 / 34

CSE 12 – Basic Data Structures

Download Presentation

CSE 12 – Basic Data Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS2 in Java Peer Instruction Materials by Cynthia Lee is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.Based on a work at http://peerinstruction4cs.org.Permissions beyond the scope of this license may be available at http://peerinstruction4cs.org. CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12

  2. Reading Quiz! • The Iterator design pattern helps you access elements of a Collection, in a way common to all Collections. • TRUE! • FALSE!

  3. Reading Quiz! 2) Composition creates an 'is-a' relationship and Inheritance creates a 'has-a' relationship. • TRUE! • FALSE!

  4. Reading Quiz! 3) In Java, if A is an Interface, you cannot create a new instance of type A.  • TRUE! • FALSE!

  5. Review of Thursday: Inheritance! * Types * Visibility

  6. Which is legal? A: Base b=new Base(); Derived d=b; B: Derived d=new Derived(); Base b=d; C: Base b=new Derived(); D: Derived d=new Base(); E: Other/none/more public class Base { protected int x; } public class Derived extends Base { protected int y; }

  7. True, False, or Mostly True Public methods are the only part of your class that clients can access and use. • TRUE! • FALSE! • Mostly! (true but incomplete)

  8. True, False, or Mostly True Public methods are the only part of your class that clients can access and use. C: Mostly (true but incomplete) Clients can also use any public instance variables, and subclasses can use any protected instance variables. Be aware that your clients may create subclasses of your classes!

  9. Step 1 of HW Java’s JUnit system

  10. Unit testing with the swingui of Junit 3.8.1: all tests passed The green bar of happiness; all tests passed! Names of the testing methods corresponding to the test cases you prepared. A green check mark means the test passed.

  11. When one or more tests fail The red bar of sadness; some tests failed Names of the testing methods in your test suite. A red X means the test failed. Stack trace telling what was expected, what was generated and where the test failed; very handy!

  12. JUnit basics To do unit testing in the Junit framework: Define a subclass of junit.framework.TestCase Optional: Define instance variables that store the state of the “test fixture”, i.e. the objects that will be tested Initialize the fixture state by overriding the setUp() instance method Clean-up the fixture state after a test by overriding the tearDown() instance method Define public void no-argument methods with names that start with test. Each “testXXX” method should be written to test a particular aspect of the test fixture Define a main() method to run your TestCase class as a program

  13. TestCase and test fixtures Define a subclass of junit.framework.TestCase Define instance variables that store the state of the “test fixture”, i.e. the objects that will be tested import junit.framework.*; public class RectangleTester extends TestCase { private Rectangle r1, r2; // test fixtures To inherit the testing and test run methods we will need

  14. setUp() and tearDown() /* Called AUTOMATICALLY before each testXXX() method is run */ protected void setUp() { r1 = new Rectangle(); r2 = new Rectangle(2.0,3.0); } /* Called AUTOMATICALLY after each testXXX() method is run */ protected void tearDown() { r1 = null; r2 = null; } Make sure each test method starts with a clean copy of the test fixture. setup(); testXXX(); teardown(); This is the sequence of calls the JUnit framework does for you automatically for each test method testXXX() that is invoked.

  15. Coding a test case as a “testXXX” method /** Test case 2.1: verify that default constructor sets default instance variable values correctly */ public void testDefaultInstance() { assertEquals(1.0,r1.getLength()); assertEquals(1.0,r1.getHeight()); } Remember: setUp() will be called prior to each test method getting called, creating test object r1 anew for each test /** Test case 2.6: verify that mutator for length throws * exception on illegal input. */ public void testMutatorIllegalInput() { try { r1.setLength(0); // 0 is illegal, should throw fail(); } catch (IllegalArgumentException e) { // test passes } }

  16. Running your TestCase class To run a class as a program, the class must have a public static void main() method. Here are two ways to define it in the Junit 3.8.1 framework, depending on whether you want a GUI or text version: /** Run RectangleTester as a gui application */ public static void main(String args[]) { junit.swingui.TestRunner.main(new String[] {“RectangleTester”}); } /** Run RectangleTester as a text console application */ public static void main(String args[]) { junit.textui.TestRunner.main(new String[] {“RectangleTester”}); }

  17. More JUnit basics Test fixture instance variables are optional: you can do the same thing with local variables inside the test methods If you are not using test fixture instance variables, you do not need to define setUp() and tearDown() either When you run your TestCase class as a program, each “testXXX” method is called automatically… If a Junit assertion fails when a testXXX method runs, that test fails If testXXX method throws an exception, that is considered an error, not a test failure! If a testXXX method returns normally, that test passes

  18. JUnit 3.8.1 assertion methods The JUnit framework provides many useful assertion methods to use in your testXXX() methodsassertEquals(x,y) // fail if x is not equal to yassertTrue(b) // fail if b has boolean value falseassertFalse(b) // fail if b has boolean value trueassertSame(x,y) // fail if x and y point to different objectsassertNotSame(x,y) // fail if x and y point to the same objectassertNull(x) // fail if x is not nullassertNotNull(x) // fail if x is nullfail() // always fails All these assertion methods are overloaded with a version that takes an additional first argument of type String, a message which will be printed out in some contexts

  19. Speaking of equality… =

  20. Consider the following class for a Ninja public class Ninja { private int honor; public Ninja(int h) { this.honor=h; } }

  21. Using the Ninja class: Ninja n1=new Ninja(50); Ninja n2=new Ninja(50); n1 n2 honor: 50 honor: 50

  22. n1 n2 honor: 50 honor: 50 True, False, or It Depends? n1 == n2 A: True B: False C: It Depends

  23. n1 n2 honor: 50 honor: 50 True, False, or It Depends? • n1.equals(n2) A: True B: False C: It Depends

  24. Default implementation of equals() in the Java source code: public boolean equals(Object obj) { return (this == obj); } If you don't override equals, this is the default version you inherit! Which is really same as using ==

  25. Improved Ninja class public class Ninja { private int honor; public Ninja(int h) { this.honor=h; } public boolean equals(Ninja other) { return this.honor == other.honor; } }

  26. n1 n2 honor: 50 honor: 50 Using the improved Ninja class n1.equals(n2) is now True!

  27. True, False, or It Depends? Object o1=new Ninja(50); Ninja n2=new Ninja(50); o1.equals(n2); A: True B: False C: It Depends

  28. You must override the equals() method inherited from Object! public class Ninja { ... public boolean equals(Object other) { if (!(other instanceof Ninja)) { return false; } Ninja o=(Ninja)other; return this.honor == o.honor; } }

  29. Iterators Next!

  30. The Iterator Software Design Pattern • A common situation: A client needs to inspect the data elements in a collection, without wanting to know details of how the collection structures its data internally • Solution: • Define an interface that specifies how an iterator will behave • Design the collection to be able to supply an object that implements that iterator interface • A client then can ask the collection for an iterator object, and use that iterator to inspect the collection’s elements, without having to know how the collection is implemented

  31. Iterable<E> Interface TheCollection<E>interface extends the Iterable<E>interface, which is defined as follows: public interface Iterable<E> { public Iterator<E> iterator(); } So any class that implements Collection<E>must define an instance method iterator() that returns an Iterator<E>object for that instance And Iterator<E> is also an interface in the JCF…

  32. Iterator<E> Interface TheIterator<E>interface is defined as follows: public interface Iterator<E> { public E next(); public booleanhasNext(); public void remove(); } So, any object that is-a Iterator<E> will have those operations as part of its API. But what are these methods supposed to do? Let’s look at the documentation, and some examples

  33. WHY have iterators? What is the difference between these codes? Note: ls is some object of a type that implements List<MyObjs> Iterator version Increment version inti=0; while (i<c.size()) { MyObjs x = ls.get(i); //do something with x i++; } Iterator<MyObjs> i = ls.iterator(); while (i.hasNext()) { MyObjs x = i.next(); //do something with x } No difference: they are totally equivalent Difference: Increment will run faster Difference: Iterator will run faster No difference: Java just likes having iterators to make students’ lives harder Other/none/more

  34. WHY have iterators? • Linked List • To go to nth element, you must start at the beginning and go through one at a time until you get to the nth one • A pain to start over vs just having the iterator keep your place like a bookmark • Trees • To go to the “nth” element, you must travel around the tree in some planned way • A pain to start over vs just having the iterator keep your place in the journey

More Related