HELP/FAQ


Software Development and Abstract Data Types: PART II

Chapters 1-3

Phases of Software Development

Abstract Data Types

Information hiding – separation of specification from implementation

Abstract Data Type –
A mathematical specification of a data structure that specifies:

the type of data stored

the operations supported on that data

the types of parameters of the operations

An ADT specifies what, but not how

Example 1: Location ADT

 

Specification – p.63

Constructor

public Location(double xInitial, double yInitial)

Construct a location with specified coordinates.

Parameters:

xInitial – the initial x coordinate of this Location

yInitial – the initial y coordinate of this Location

Postcondition:

This Location has been initialized at the given coordinates.

Specification (cont’d)

clone

public Object clone()

Generate a copy of this Location.

Returns:
The return value is a copy of this Location.

Special note:
The return value must be typecast to a Location before it can be used.

Specification (cont’d)

distance

public static double distance(Location p1, Location p2)

Compute the distance between two Locations.

Parameters:
p1 – the first Location
p2 – the second Location

Returns: The distance between p1 and p2.

Special Note: Returns Double.NaN if either Location is null.

Specification (cont’d)

equals

public boolean equals (Object obj)

Compare this Location to another for equality.

Parameters:
obj – an object with which this Location is compared

Returns: True if obj refers to the same Location as this Location object. False otherwise.

Special Note: Returns false if obj is null or not a Location object.

Specification (cont’d)

getX (and getY)

public double getX( ) ( or getY() )

Get the x (or y) coordinate of this Location

Returns: the x (or y) coordinate of this location




Specification (cont’d)

midpoint

public static Location midpoint(Location p1, Location p2)

Generates and returns a Location halfway between two Locations

Parameters:
p1 – the first Location
p2 – the second Location

Returns: a Location halfway between p1 and p2

Special note: Returns null if either p1 or p2 is null.

Specification (cont’d)

rotate90

public void rotate90()

Rotate this Location 90 degrees in a clockwise fashion around the origin

Postcondition: This Location has been rotated clockwise 90 degrees around the origin


Specification (cont’d)

shift

public void shift(double xAmount, double yAmount)

Move this location by given amounts along the x and y axes.

Postcondition: This location has been moved by the given amounts along the two axes.

Special note: (see text)

Specification (cont’d)

toString

public String toString()

Generate a string representation of this Location object.

Returns: a string representation of this Location



Method Types

Accessor method – returns information about the state of an object without altering the state of the object [getX, getY]

Modification (mutator) method – may change the state of an object through its invocation [rotate90, shift]

Static method – returns information about a set of one or more objects [distance, midpoint]

Support method – provides common support for objects [the constructor, clone, equals, toString]

Implementation – p. 65

public class Location implements Cloneable

{

    private double x; // state variables
    private double y;

    public Location (double xInitial, double yInitial) // constructor
    {

        x = xInitial;

        y = yInitial;

    }

Implementation (cont’d)

    public Object clone()

    {

        Location answer;

        try {

            answer = (Location)super.clone();

        }

        catch (CloneNotSupportedException e){

            throw new RunTimeException("…");

        }

        return answer;

    }

Implementation (cont’d)

    public static double distance(Location p1, Location p2) {

        double a, b, c_squared;

        if ((p1==null)||(p2==null))
            return Double.NaN;

        a = p1.x – p2.x;

        b = p1.y – p2.y;

        c_squared = a*a + b*b;

        return Math.sqrt(c_squared);

    }

Implementation (cont’d)

    public boolean equals(Object obj)

    {

        if (obj instanceof Location)
        {
            Location candidate = (Location) obj;
            return (candidate.x == x) && (candidate.y == y);
        }

    else
        return false;

    }

Implementation (cont’d)

    public double getX()

    {

        return x;

    }

    public double getY()

    {

        return y;

    }

Implementation (cont’d)

    public static Location midpoint Location p1, Location p2) 

      {

        double xMid, yMid;

        if ((p1==null)||(p2==null))
            return null;

        xMid = (p1.x/2)+(p2.x/2);
        yMid = (p1.y/2)+(p2.y/2);
        Location answer =
            new Location(xMid, yMid);
        return answer;

    }

Implementation (cont’d)

    public void rotate90() {

        double xNew, yNew;

        xNew = y;
        yNew = -x;
        x = xNew;
        y = yNew;

    }


Implementation (cont’d)

    public void shift(double xAmount, double yAmount) {

        x += xAmount;
        y += yAmount;

    }

    public String toString()

    {

        return "(x=" + x + " y=" + y + ")";

    }

} // end class Location

Use of Location ADT

class LocationTester {
public static void main(String[] args)

{

    Location server = new Location(2.0,4.5);

    Location mobile = (Location) server.clone();

    mobile.shift(-3.0, -3.0);

    System.out.println("The devices are " +

        Location.distance(server, mobile) +

        " blocks away from each other.");



etc.

Example 2: Bag ADT

Bag: A collection of items of the same type.

•A specific item may appear any number of times in a bag.

•A bag is not a set.

•A bag is not ordered.

•The items of a bag will be stored in an array (for now).

•A bag may have limited size due to memory constraints.

 

 

Specification – p.107

Constructors

public IntArrayBag( )

public IntArrayBag(int initialCapacity)

Construct a bag of integers with capacity 10 (default) or initialCapacity.

Precondition: initialCapacity > 0

Postcondition: This bag is empty and has an initial capacity.

Throws: IllegalArgumentException, OutOfMemoryError

Specification (cont’d)

getCapacity

public int getCapacity()

Determines the current capacity of this bag.

Returns: the current capacity of this bag.

size

public int size()

Determines the number of elements in this bag.

Returns: the number of elements in this bag.

Specification (cont’d)

ensureCapacity

public void ensureCapacity
(int minimumCapacity)

Change the current capacity of this bag.

Parameters: minimumCapacity – the new capacity for this bag

Postcondition: This bag’s capacity has been changed to minimumCapacity, if this is greater than its current capacity.

Throws: OutOfMemoryException

Specification (cont’d)

add

public void add(int element)

Add a new element to this bag.

Parameters:
element – the new element being added to the bag

Postcondition: A new copy of the element has been added to this bag.

Special Note: If the new element cannot be stored in the bag at its current capacity, the bag’s capacity is increased.

Throws: OutOfMemoryError

Specification (cont’d)

addAll

public void addAll(IntArrayBag addend)

Add the contents of another bag to this bag.

Parameters:
addend – a bag whose contents will be added to this bag

Postcondition: This bag will contain its original contents and the contents of the other bag.

Throws: NullPointerException, OutOfMemoryError

Specification (cont’d)

union

public static IntArrayBag union
(IntArrayBag b1, IntArrayBag b2)

Create a new bag that contains all the elements from two other bags.

Parameters:
b1 – the first of two bags
b2 – the second of two bags

Precondition: neither b1 nor b2 is null

Returns: A new bag that is the union of b1 and b2

Throws: NullPointerException, OutOfMemoryError

Specification (cont’d)

countOccurrences

public int countOccurrences(int target)

Count the number of occurrences of a particular value in this bag.

Parameters:
target – the element that needs to be counted

Returns: The number of times the target is in this bag.

Specification (cont’d)

remove

public boolean remove(int target)

Remove one copy of a specified element from this bag.

Parameter:

target – the element search for in this bag for removal

Postcondition: If the target was found in this bag, then one copy is removed and the method returns true. Otherwise, this bag remains unchanged and the method returns false.

Specification (cont’d)

trimToSize

public void trimToSize()

Reduce the current capacity of this bag to its actual size.

Postcondition: This bag’s capacity has been changed to its current size.

Throws: OutOfMemoryError

Specification (cont’d)

clone

public Object clone()

Generate a copy of this bag.

Returns:
The return value is a copy of this bag.

Special note:
The return value must be typecast to an IntArrayBag before it can be used.

Throws: OutOfMemoryError

Invariant of the ADT

An invariant is a condition that remains true before and after some operation is performed (i.e. precondition = postcondition)

All the methods of an ADT (except the constructors) must ensure that the invariant of the ADT is valid before and after execution.

Invariant of the Bag ADT

Let data = the array that holds the bag items

Let data.length = the capacity of the array

Let manyItems = the number of items in the bag (i.e. its size)

INVARIANTS:

The elements of a bag are stored in data[0..manyItems-1].

manyItems < data.length

Implementation – p. 113

public class IntArrayBag implements Cloneable

{

    private int[] data;
    private int manyItems;

Implementation (cont’d)

    public IntArrayBag(int initialCapacity) {

        if (initialCapacity < 0)
            throw new IllegalArgumentException();
        manyItems = 0;
        data = new int[initialCapacity];

    }

    public IntArrayBag() {

        manyItems = 0;
        data = new int[10];

    }

Implementation (cont’d)

    public int getCapacity() {

        return data.length;

    }

    public int size() {

        return manyItems;

    }

Sidenote: System.arraycopy

System.arraycopy(A,B,C,D,E);

A = reference of array to copy FROM

B = starting position to copy FROM

C = reference of array to copy TO

D = starting position to copy TO

E = how many elements to copy

Implementation (cont’d)

    public void ensureCapacity(int minimumCapacity) {

        int biggerArray[];

        if (data.length < minimumCapacity) {

            biggerArray = new int[minimumCapacity];

            System.arrayCopy(data, 0, biggerArray, 0, manyItems);

            data = biggerArray;

        }

    }

Implementation (cont’d)

    public void add(int element) {

        if (manyItems == data.length)

        ensureCapacity(manyItems*2+1);

        data[manyItems] = element;

        manyItems++;

    }


Implementation (cont’d)

    public void addAll(IntArrayBag addend) {

        ensureCapacity(manyItems + addend.manyItems);
        System.arraycopy(addend.data, 0, data,
            manyItems, addend.manyItems);

        manyItems += addend.manyItems;

    }

Implementation (cont’d)

    public static IntArrayBag union
        (IntArrayBag b1, IntArrayBag b2) 
    {
        IntArrayBag answer = new IntArrayBag
            (b1.getCapacity()+ b2.getCapacity());
        System.arraycopy(b1.data,0,answer.data, 0,b1.manyItems);
        System.arraycopy(b2.data,0,answer.data, 
            b1.manyItems, b2.manyItems);

        answer.manyItems = b1.manyItems + b2.manyItems;
        return answer;

    }

Implementation (cont’d)

    public int countOccurrences(int target)

    {
        int answer = 0;
        int index;
        for (index = 0; index < manyItems; index++)
        {
            if (target == data[index])
                answer++;
        }
        return answer;

    }

Implementation (cont’d)

    public boolean remove(int target) {
        int index = 0;
        while ((index < manyItems) && (target != data[index]))
            index++;
        if (index == manyItems)
            return false;
        else {
            manyItems--;
            data[index] = data[manyItems];
            return true;
        }

    }

Implementation (cont’d)

    public void trimToSize() {
        int trimmedArray[];
        if (data.length != manyItems) {
            trimmedArray = new int[manyItems];
            System.arraycopy(data,0, trimmedArray, 0,manyItems);
            data = trimmedArray;
        }

    }

Implementation (cont’d)

    public Object clone() {
        IntArrayBag answer;
        try {
            answer = (IntArrayBag)super.clone();
        }
        catch (CloneNotSupportedException e) {
            throw new RunTimeException("...");
        }
        answer.data = (int []) data.clone();
        return answer;

    }

} // end class IntArrayBag

Order of Complexity

Given a bag with n items and capacity c.

add

Without a capacity increase: O(1)

With a capacity increase: O(n)

countOccurrences O(n)

getCapacity O(1)

remove O(n)

clone O(c)

 


Course Info | Schedule | Sections | Announcements | Homework | Exams | Help/FAQ | Grades | HOME