源代码:
package
{
import flash.display.Sprite;
/**
* 测试复杂对象的排序
* @author Jave.Lin(afeng)
**/
public class TestComplexSort extends Sprite
{
public function TestComplexSort()
{
super();
var lastNameArr:Vector.<String>=new Vector.<String>();
lastNameArr.push("Lin","Smith","Steven","Abros","BB","CCC","D","EE","FF","GG","Gates","HH");
var firstNameArr:Vector.<String>=new Vector.<String>();
firstNameArr.push("Jave","John","Harry","Waston","Bill","Tom","Jerry");
var ageMax:uint=150;
var personArr:Vector.<Person>=new Vector.<Person>();
for (var i:int = 0; i < 10; i++)
{
var p:Person=new Person();
p.firstName=firstNameArr[Math.floor(Math.random()*firstNameArr.length)];
p.lastName=lastNameArr[Math.floor(Math.random()*lastNameArr.length)];
p.age=Math.floor(Math.random()*ageMax);
personArr[i]=p;
}
trace(personArr);
personArr.sort(comparePerson);
trace(personArr);
}
private function comparePersonAge(a:Person,b:Person):int
{
if(a.age>b.age)return 1;
else if(a.age<b.age)return -1;
return 0;
}
private function comparePersonFirstName(a:Person,b:Person):int
{
if(a.firstName>b.firstName)return 1;
else if(a.firstName<b.firstName)return -1;
return 0;
}
private function comparePersonLastName(a:Person,b:Person):int
{
if(a.lastName>b.lastName)return 1;
else if(a.lastName<b.lastName)return -1;
return 0;
}
private function comparePerson(a:Person,b:Person):int
{
var result:int=0;
//这里的排序权重:即:顺序的先后,现在这里是以:FirstName为最优条件
//当然你也可以试着换一下排序函数的顺序,即可看到效果。
result=comparePersonFirstName(a,b);
if(result!=0)return result;
result=comparePersonLastName(a,b);
if(result!=0)return result;
result=comparePersonAge(a,b);
if(result!=0)return result;
return 0;
}
}
}
class Person
{
public var lastName:String;
public var firstName:String;
public var age:uint;
public function toString():String
{
return firstName+"."+lastName+" age:"+age;
}
}
输出:
Harry.D age:43,Waston.FF age:35,Waston.EE age:136,Jave.FF age:94,John.BB age:135,Waston.CCC age:41,Bill.GG age:139,John.BB age:93,Waston.FF age:44,Jave.HH age:65
Bill.GG age:139,Harry.D age:43,Jave.FF age:94,Jave.HH age:65,John.BB age:93,John.BB age:135,Waston.CCC age:41,Waston.EE age:136,Waston.FF age:35,Waston.FF age:44