packageexample12;import javax.swing.*;classexample12 {public static voidmain(String[] args) {
example12 tester= newexample12();
tester.start();
}private voidstart() {
String[] name= { "ape", "cat", "bee", "bat", "eel", "dog", "gnu","yak", "fox", "cow", "hen", "tic", "man"};
Person p;
AddressBook ab;int version = Integer.parseInt(JOptionPane.showInputDialog(null,"有三种方法可以实现Person对象排序,请输入数字(1-3):"));switch(version) {case 1:
ab= newAddressBookVer1();break;case 2:
ab= newAddressBookVer2();break;case 3:
ab= newAddressBookVer3();break;default:
ab= newAddressBookVer1();break;
}
System.out.println("输入数据:");for (int i = 0; i < name.length; i++) {
p= new Person(name[i], random(10, 50), random(0, 1) == 0 ? 'M':'F'); //if(random(0,1) ==0) 'M' else 'F'
ab.add(p);
System.out.println(p.toString());
}
System.out.println(" ");
Person[] sortedlist=ab.sort(Person.AGE);
System.out.println("按年龄排序:");for (int i = 0; i < sortedlist.length; i++) {
System.out.println(sortedlist[i].toString());
}
System.out.println(" ");
sortedlist=ab.sort(Person.NAME);
System.out.println("按姓名排序:");for (int i = 0; i < sortedlist.length; i++) {
System.out.println(sortedlist[i].toString());
}
}private int random(int low, inthigh) {return (int) Math.floor(Math.random() * (high - low + 1)) +low;
}
}
AddressBook类:packageexample12;interfaceAddressBook {public voidadd( Person newPerson );public booleandelete( String searchName );publicPerson search( String searchName );public Person[ ] sort ( intattribute );
}
Person类:packageexample12;classPerson {public static final int NAME = 0;public static final int AGE = 1;private static final int LESS = -1;private static final int EQUAL = 0;private static final int MORE = 1;private static intcompareAttribute;privateString name;private intage;private chargender;static{
compareAttribute=NAME;
}publicPerson() {this("Not Given", 0, 'U');
}public Person(String name, int age, chargender) {this.age =age;this.name =name;this.gender =gender;
}public static void setCompareAttribute( intattribute ) {
compareAttribute=attribute;
}public int compareTo( Person person, intattribute ) {intcomparisonResult;if ( attribute ==AGE ) {int p2age =person.getAge( );if (this.age
comparisonResult=LESS;
}else if (this.age ==p2age) {
comparisonResult=EQUAL;
}else{assert this.age >p2age;
comparisonResult=MORE;
}
}else { //compare the name using the String class抯//compareTo method
String p2name =person.getName( );
comparisonResult= this.name.compareTo(p2name);
}returncomparisonResult;
}public intcompareTo( Person person ) {returncompareTo(person, compareAttribute);
}public intgetAge( ) {returnage;
}public chargetGender( ) {returngender;
}publicString getName( ) {returnname;
}public void setAge( intage ) {this.age =age;
}public void setGender( chargender ) {this.gender =gender;
}public voidsetName( String name ) {this.name =name;
}publicString toString( ) {return this.name + "\t\t" +
this.age + "\t\t" +
this.gender;
}
}
AddressBookVer1类:packageexample12;class AddressBookVer1 implementsAddressBook {private static final int DEFAULT_SIZE = 25;private static final int NOT_FOUND = -1;privatePerson[] entry;private intcount;publicAddressBookVer1( )
{this( DEFAULT_SIZE );
}public AddressBookVer1( intsize )
{
count= 0;if (size <= 0 ) { //invalid data value, use default
throw new IllegalArgumentException("Size must be positive");
}
entry= newPerson[size];//System.out.println("array of "+ size + " is created.");//TEMP
}public voidadd(Person newPerson)
{if (count == entry.length) { //no more space left,
enlarge( ); //create a new larger array
}//at this point, entry refers to a new larger array
entry[count] =newPerson;
count++;
}public booleandelete( String searchName )
{booleanstatus;intloc;
loc=findIndex( searchName );if (loc ==NOT_FOUND) {
status= false;
}else { //found, pack the hole
entry[loc]= entry[count-1];
status= true;
count--; //decrement count,//since we now have one less element
}returnstatus;
}publicPerson search( String searchName )
{
Person foundPerson;int loc = 0;while ( loc < count &&
!searchName.equals( entry[loc].getName() ) ) {
loc++;
}if (loc ==count) {
foundPerson= null;
}else{
foundPerson=entry[loc];
}returnfoundPerson;
}public Person[ ] sort ( intattribute ) {if (!(attribute == Person.NAME || attribute ==Person.AGE) ) {throw newIllegalArgumentException( );
}
Person[ ] sortedList= newPerson[ count ];
Person p1, p2, temp;//copy references to sortedList
for (int i = 0; i < count; i++) {
sortedList[i]=entry[i];
}//set the comparison attribute
entry[0].setCompareAttribute( attribute );//begin the bubble sort on sortedList
intbottom, comparisonResult;boolean exchanged = true;
bottom= sortedList.length - 2;while( exchanged ) {
exchanged= false;for (int i = 0; i <= bottom; i++) {
p1=sortedList[i];
p2= sortedList[i+1];//comparisonResult = p1.compareTo( p2, attribute );
comparisonResult=p1.compareTo( p2 );if ( comparisonResult > 0 ) { //p1 is 鎲�rger锟�//than p2, so
sortedList[i] = p2; //exchange
sortedList[i+1] =p1;
exchanged= true; //exchange is made
}
}
bottom--;
}returnsortedList;
}private voidenlarge( )
{//create a new array whose size is 150% of//the current array
int newLength = (int) (1.5 *entry.length);
Person[] temp= newPerson[newLength];//now copy the data to the new array
for (int i = 0; i < entry.length; i++) {
temp[i]=entry[i];
}//finally set the variable entry to point to the new array
entry =temp;//System.out.println("Inside the method enlarge");//TEMP//System.out.println("Size of a new array: " + entry.length);//TEMP
}private intfindIndex( String searchName )
{int loc = 0;while ( loc < count &&
!searchName.equals( entry[loc].getName() ) ) {
loc++;
}if (loc ==count) {
loc=NOT_FOUND;
}returnloc;
}
}
AddressBookVer2类:packageexample12;import java.util.*;class AddressBookVer2 implementsAddressBook {private static final int DEFAULT_SIZE = 25;private static final int NOT_FOUND = -1;privatePerson[] entry;private intcount;publicAddressBookVer2( ) {this( DEFAULT_SIZE );
}public AddressBookVer2(intsize) {
count= 0;if (size <= 0 ) { //invalid data value, use default
throw new IllegalArgumentException("Size must be positive");
}
entry= newPerson[size];//System.out.println("array of "+ size + " is created.");//TEMP
}public voidadd( Person newPerson ) {if (count == entry.length) { //no more space left,
enlarge( ); //create a new larger array
}//at this point, entry refers to a new larger array
entry[count] =newPerson;
count++;
}public booleandelete( String searchName ) {booleanstatus;intloc;
loc=findIndex( searchName );if (loc ==NOT_FOUND) {
status= false;
}else { //found, pack the hole
entry[loc]= entry[count-1];
status= true;
count--; //decrement count,//since we now have one less element
}returnstatus;
}publicPerson search( String searchName ) {
Person foundPerson;int loc = 0;while ( loc < count &&
!searchName.equals( entry[loc].getName() ) ) {
loc++;
}if (loc ==count) {
foundPerson= null;
}else{
foundPerson=entry[loc];
}returnfoundPerson;
}public Person[ ] sort ( intattribute ) {if (!(attribute == Person.NAME || attribute ==Person.AGE) ) {throw newIllegalArgumentException( );
}
Person[ ] sortedList= newPerson[ count ];//copy references to sortedList
for (int i = 0; i < count; i++) {
sortedList[i]=entry[i];
}
Arrays.sort(sortedList, getComparator(attribute));returnsortedList;
}private voidenlarge( )
{//create a new array whose size is 150% of//the current array
int newLength = (int) (1.5 *entry.length);
Person[] temp= newPerson[newLength];//now copy the data to the new array
for (int i = 0; i < entry.length; i++) {
temp[i]=entry[i];
}//finally set the variable entry to point to the new array
entry =temp;//System.out.println("Inside the method enlarge");//TEMP//System.out.println("Size of a new array: " + entry.length);//TEMP
}private intfindIndex( String searchName )
{int loc = 0;while ( loc < count &&
!searchName.equals( entry[loc].getName() ) ) {
loc++;
}if (loc ==count) {
loc=NOT_FOUND;
}returnloc;
}private Comparator getComparator(intattribute) {
Comparator comp= null;if (attribute ==Person.AGE) {
comp= newAgeComparator( );
}else{assert attribute ==Person.NAME:"Attribute not recognized for sorting";
comp= newNameComparator( );
}returncomp;
}class AgeComparator implementsComparator {private final int LESS = -1;private final int EQUAL = 0;private final int MORE = 1;public intcompare(Object p1, Object p2) {intcomparisonResult;int p1age =((Person)p1).getAge( );int p2age =((Person)p2).getAge( );if (p1age
comparisonResult=LESS;
}else if (p1age ==p2age) {
comparisonResult=EQUAL;
}else{assert p1age >p2age;
comparisonResult=MORE;
}returncomparisonResult;
}
}class NameComparator implementsComparator {public intcompare(Object p1, Object p2) {
String p1name=((Person)p1).getName( );
String p2name=((Person)p2).getName( );returnp1name.compareTo(p2name);
}
}
}
AddressBookVer3类:packageexample12;import java.util.*;class AddressBookVer3 implementsAddressBook {private static final int DEFAULT_SIZE = 25;privateMap entry;publicAddressBookVer3( ) {this( DEFAULT_SIZE );
}public AddressBookVer3(intsize) {
entry= newHashMap(size);//System.out.println("array of "+ size + " is created.");//TEMP
}public voidadd( Person newPerson ) {
entry.put(newPerson.getName(), newPerson);
}public booleandelete( String searchName ) {booleanstatus;
Person p=(Person) entry.remove(searchName);if (p == null) {
status= false;
}else{
status= true;
}returnstatus;
}publicPerson search( String searchName ) {return(Person) entry.get(searchName);
}public Person[ ] sort ( intattribute ) {if (!(attribute == Person.NAME || attribute ==Person.AGE) ) {throw newIllegalArgumentException( );
}
Person[ ] sortedList= newPerson[entry.size()];
entry.values().toArray(sortedList);
Arrays.sort(sortedList, getComparator(attribute));returnsortedList;
}private Comparator getComparator(intattribute) {
Comparator comp= null;if (attribute ==Person.AGE) {
comp= newAgeComparator( );
}else{assert attribute ==Person.NAME:"Attribute not recognized for sorting";
comp= newNameComparator( );
}returncomp;
}class AgeComparator implementsComparator {private final int LESS = -1;private final int EQUAL = 0;private final int MORE = 1;public intcompare(Object p1, Object p2) {intcomparisonResult;int p1age =((Person)p1).getAge( );int p2age =((Person)p2).getAge( );if (p1age
comparisonResult=LESS;
}else if (p1age ==p2age) {
comparisonResult=EQUAL;
}else{assert p1age >p2age;
comparisonResult=MORE;
}returncomparisonResult;
}
}class NameComparator implementsComparator {public intcompare(Object p1, Object p2) {
String p1name=((Person)p1).getName( );
String p2name=((Person)p2).getName( );returnp1name.compareTo(p2name);
}
}
}