cse 12 – basic data structures

34
CSE 12 – Basic Data Structures Cynthia 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.or g . Permissions beyond the scope of this license may be available at http://peerinstruction4cs.or g .

Upload: ava-contreras

Post on 30-Dec-2015

35 views

Category:

Documents


0 download

DESCRIPTION

- PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CSE 12 – Basic Data Structures

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.

Page 2: CSE 12 – Basic Data Structures

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!

Page 3: CSE 12 – Basic Data Structures

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

A. TRUE!B. FALSE!

Page 4: CSE 12 – Basic Data Structures

Reading Quiz!

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

A. TRUE!B. FALSE!

Page 5: CSE 12 – Basic Data Structures

Review of Thursday: Inheritance!* Types* Visibility

Page 6: CSE 12 – Basic Data Structures

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

Page 7: CSE 12 – Basic Data Structures

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)

Page 8: CSE 12 – Basic Data Structures

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!

Page 9: CSE 12 – Basic Data Structures

Step 1 of HWJava’s JUnit system

Page 10: CSE 12 – Basic Data Structures

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

Page 11: CSE 12 – Basic Data Structures

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

Page 12: CSE 12 – Basic Data Structures

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

Page 13: CSE 12 – Basic Data Structures

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

Page 14: CSE 12 – Basic Data Structures

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

Page 15: CSE 12 – Basic Data Structures

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

Page 16: CSE 12 – Basic Data Structures

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

Page 17: CSE 12 – Basic Data Structures

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

Page 18: CSE 12 – Basic Data Structures

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

Page 19: CSE 12 – Basic Data Structures

Speaking of equality…=

Page 20: CSE 12 – Basic Data Structures

Consider the following class for a Ninja

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

this.honor=h;}

}

Page 21: CSE 12 – Basic Data Structures

Using the Ninja class:

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

honor: 50

n1

honor: 50

n2

Page 22: CSE 12 – Basic Data Structures

honor: 50

n1

honor: 50

n2

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

A: True B: False C: It Depends

Page 23: CSE 12 – Basic Data Structures

honor: 50

n1

honor: 50

n2

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

A: True B: False C: It Depends

Page 24: CSE 12 – Basic Data Structures

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

Page 25: CSE 12 – Basic Data Structures

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

}

Page 26: CSE 12 – Basic Data Structures

honor: 50

n1

honor: 50

n2

Using the improved Ninja class

n1.equals(n2)

is now True!

Page 27: CSE 12 – Basic Data Structures

True, False, or It Depends?

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

o1.equals(n2);

A: TrueB: FalseC: It Depends

Page 28: CSE 12 – Basic Data Structures

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;

}}

Page 29: CSE 12 – Basic Data Structures

IteratorsNext!

Page 30: CSE 12 – Basic Data Structures

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

Page 31: CSE 12 – Basic Data Structures

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…

Page 32: CSE 12 – Basic Data Structures

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

Page 33: CSE 12 – Basic Data Structures

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>

Page 34: CSE 12 – Basic Data Structures

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