static int findA (int [] a, int val) { for (int i = 0; i < a.length; i++) { if (a[i] == val) return i; } return a.length; } static int findB (int [] a, int val) { for (int i = a.length -1 ; i >= 0; i--) { if (a[i] == val) return i; } return -1; }
val
is either missing or appears
more than once.requires: val occurs in a effects: returns result such that a[result] = val
public StringBuffer reverse() // modifies: this // effects: Let n be the length of the old character sequence, the // one contained in the string buffer just prior to execution of the // reverse method. Then the character at index k in the new // character sequence is equal to the character at index n-k-1 in // the old character sequence. //Or, more formally //effects: length (this.seq) = length (this.seq ) //for all k: 0..length(this.seq)-1 | this.seq [k] = //this.seq[length(this.seq)-k-1]
public boolean startsWith(String prefix) // Tests if this string starts with the specified prefix. // effects: // if (prefix = null) throws NullPointerException // else returns true iff exists a sequence s such that (prefix.seq ^ // s = this.seq) public String substring(int i) // effects: // if i < 0 or i > length (this.seq) throws IndexOutOfBoundsException // else returns r such that // some sequence s | length(s) = i && s ^ r.seq = this.seq
/*This one does not determine the outcome but it is still useful to clients. */ public boolean maybePrime () // effects: if this BigInteger is composite, returns false /*Same here, we don't know in which order they will be notified */ public void addObserver(Observer o) // modifies: this // effects: this.observers = this.observers + {o} public void notifyObservers() // modifies the objects in this.observers // effects: calls o.notify on each observer o in this.observers
Vector
is mutable but
String
is immutable. public class List { public List (); public void add (int i, Object e); public void set (int i, Object e); // modifies this // effects // throws IndexOutOfBoundsException if i < 0 or i >= length (this.elems) // else this.elems [i] = e and this.elems unchanged elsewhere public void remove (int i); public int size (); public Object get (int i); // throws // IndexOutOfBoundsException if i < 0 or i > length (this.elems) // returns // this.elems [i] public void add (int i, Object e); }
Vector v = new Vector(); List l = new List (); .... v.copyInto (l.elementData);
class List { public Entry getEntry (int i); } //we can now write Entry e = l.getEntry (i); e.element = x; ... e.element = y;
private
to prevent access to data
members. interfaces
to achieve representation
independence.
This talk available at http://jmvidal.cse.sc.edu/talks/specifications/
Copyright © 2009 José M. Vidal
.
All rights reserved.
18 January 2005, 10:44AM