cse 12 – basic data structures

Post on 30-Dec-2015

37 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

- PowerPoint PPT Presentation

TRANSCRIPT

CSE 12 – Basic Data StructuresCynthia Bailey Lee

Some slides and figures adapted from Paul Kube’s CSE 12

                          

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.

Reading Quiz!

1) The Iterator design pattern helps you access elements of a Collection, in a way common to all Collections.

A. TRUE!B. FALSE!

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

A. TRUE!B. FALSE!

Reading Quiz!

3) In Java, if A is an Interface, you cannot create a new instance of type A. 

A. TRUE!B. FALSE!

Review of Thursday: Inheritance!* Types* Visibility

Which is legal?

public class Base{protected int x;

}

public class Derived extends Base

{protected int y;

}

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

True, False, or Mostly True

Public methods are the only part of your class that clients can access and use.

A. TRUE!B. FALSE!C. Mostly! (true but incomplete)

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!

Step 1 of HWJava’s JUnit system

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 methodscorresponding to the test casesyou prepared. A green check mark means the test passed.

10

When one or more tests fail

The red bar of sadness;some tests failed

Names of the testing methodsin your test suite. A red X means the test failed.

Stack trace telling what wasexpected, what was generated and where the test failed;very handy!

11

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

12

import junit.framework.*;

public class RectangleTester extends TestCase {

private Rectangle r1, r2; // test fixtures

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

To inherit the testing and test run methods we will need

13

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;}

setup();testXXX();teardown();

This is the sequence of calls the JUnit framework does for you automatically for each test method testXXX() that is invoked.

Make sure each test method startswith a clean copy of the test fixture.

14

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());

}

/** 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 throwfail();

} catch (IllegalArgumentException e) {// test passes

}}

Remember: setUp() will be called prior to each test method getting called, creating test object r1 anew for each test

15

Running your TestCase class

/** Run RectangleTester as a gui application */

public static void main(String args[]) { junit.swingui.TestRunner.main(new String[] {“RectangleTester”});}

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 text console application */

public static void main(String args[]) { junit.textui.TestRunner.main(new String[] {“RectangleTester”});}

16

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

17

JUnit 3.8.1 assertion methods The JUnit framework provides many useful assertion

methods to use in your testXXX() methods

assertEquals(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

18

Speaking of equality…=

Consider the following class for a Ninja

public class Ninja {private int honor;public Ninja(int h) {

this.honor=h;}

}

Using the Ninja class:

Ninja n1=new Ninja(50);Ninja n2=new Ninja(50);

honor: 50

n1

honor: 50

n2

honor: 50

n1

honor: 50

n2

True, False, or It Depends?n1 == n2

A: True B: False C: It Depends

honor: 50

n1

honor: 50

n2

True, False, or It Depends?n1.equals(n2)

A: True B: False C: It Depends

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 ==

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;}

}

honor: 50

n1

honor: 50

n2

Using the improved Ninja class

n1.equals(n2)

is now True!

True, False, or It Depends?

Object o1=new Ninja(50);Ninja n2=new Ninja(50);

o1.equals(n2);

A: TrueB: FalseC: It Depends

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;

}}

IteratorsNext!

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

4-31/36

Iterable<E> Interface The Collection<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…

4-32/36

Iterator<E> Interface The Iterator<E> interface is defined as follows:

public interface Iterator<E> { public E next();

public boolean hasNext(); 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

WHY have iterators? What is the difference between these codes?

Iterator versionIterator<MyObjs> i =

ls.iterator(); while (i.hasNext()) { MyObjs x = i.next(); //do something with x }

Increment versionint i=0;while (i<c.size()) { MyObjs x = ls.get(i); //do something with x i++; }

A. No difference: they are totally equivalentB. Difference: Increment will run fasterC. Difference: Iterator will run fasterD. No difference: Java just likes having iterators to make students’ lives harder E. Other/none/more

Note: ls is some object of a type that implements List<MyObjs>

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

top related