[source]
package
{
import flash.display.Sprite;
public class Main extends Sprite
{
var vegetables:Array = new Array();
public function Main() {
vegetables.push(new Vegetable("lettuce", 1.49));
vegetables.push(new Vegetable("spinach", 1.89));
vegetables.push(new Vegetable("asparagus", 3.99));
vegetables.push(new Vegetable("celery", 1.29));
vegetables.push(new Vegetable("squash", 1.44));
trace(vegetables);
// lettuce:1.49, spinach:1.89, asparagus:3.99, celery:1.29, squash:1.44
vegetables.sort(sortOnPrice);
trace(vegetables);
// celery:1.29, squash:1.44, lettuce:1.49, spinach:1.89, asparagus:3.99
}
private function sortOnPrice(a:Vegetable, b:Vegetable):Number {
var aPrice:Number = a.getPrice();
var bPrice:Number = b.getPrice();
if(aPrice > bPrice) {
return 1;
} else if(aPrice < bPrice) {
return -1;
} else {
//aPrice == bPrice
return 0;
}
}
}
}
class Vegetable {
private var name:String;
private var price:Number;
public function Vegetable(name:String, price:Number) {
this.name = name;
this.price = price;
}
public function getPrice():Number {
return price;
}
public function toString():String {
return " " + name + ":" + price;
}
}
[/source]