BK网络学院

首页搜索登录
首页业界网页平面多媒体程序数据库办公工具服务器系统网络安全站长认证壁纸
加入收藏 | 网站地图 | | RSS | WAP
你好,游客 登录 注册 搜索

java经典试题:通讯录排序

源程序

[日期:2013-10-18] 作者: 来源: [字体: ]

2.34 通讯录排序

2.34.1 题目:对通讯录排序。要求:扩展AddressBook类,为其引入一个排序程序。以三种不同的实现方法使新的AddressBook类可以Person对象排序(按姓名的字母表顺序或者年龄递增的顺序)。

 

2.34.2 源程序

 

package example12;

 

import Javax.swing.*;

 

class example12 {

 

    public static void main(String[] args) {

 

      example12 tester = new example12();

      tester.start();

    }

 

    private void start() {

      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 = new AddressBookVer1();

          break;

      case 2:

          ab = new AddressBookVer2();

          break;

      case 3:

          ab = new AddressBookVer3();

          break;

      default:

          ab = new AddressBookVer1();

          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, int high) {

 

      return (int) Math.floor(Math.random() * (high - low + 1)) + low;

    }

 

}

 

AddressBook类:

package example12;

 

interface AddressBook {

 

    public void add( Person newPerson );

 

    public boolean delete( String searchName );

 

    public Person search( String searchName );

 

    public Person[ ] sort ( int attribute );

 

}

 

Person类:

package example12;

 

 class Person {

 

    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 int compareAttribute;

 

    private String  name;

 

    private int    age;

 

    private char    gender;

 

    static {

 

      compareAttribute = NAME;

    }

 

    public Person() {

        this("Not Given", 0, 'U');

    }

 

    public Person(String name, int age, char gender) {

        this.age    = age;

        this.name  = name;

        this.gender = gender;

    }

 

    public static void setCompareAttribute( int attribute ) {

        compareAttribute = attribute;

    }

 

    public int compareTo( Person person, int attribute ) {

        int comparisonResult;

 

        if ( attribute == AGE ) {

            int p2age = person.getAge( );

 

            if (this.age < p2age) {

                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);

        }

 

        return comparisonResult;

    }

 

    public int compareTo( Person person ) {

 

        return compareTo(person, compareAttribute);

    }

 

    public int getAge( ) {

        return age;

    }

 

    public char getGender( ) {

        return gender;

    }

 

    public String getName( ) {

        return name;

    }

 

    public void setAge( int age ) {

        this.age = age;

    }

 

    public void setGender( char gender ) {

        this.gender = gender;

    }

 

    public void setName( String name ) {

        this.name = name;

    }

 

    public String toString( )  {

        return this.name    + "\t\t" +

              this.age    + "\t\t" +

              this.gender;

    }

}

 

AddressBookVer1类:

package example12;

 

class AddressBookVer1 implements AddressBook {

 

    private static final int  DEFAULT_SIZE = 25;

 

    private static final int  NOT_FOUND    = -1;

 

    private Person[]  entry;

 

    private int        count;

 

    public AddressBookVer1( )

    {

        this( DEFAULT_SIZE );

    }

 

    public AddressBookVer1( int size )

    {

        count = 0;

 

        if (size <= 0 ) { //invalid data value, use default

            throw new IllegalArgumentException("Size must be positive");

        }

 

        entry = new Person[size];

 

 //      System.out.println("array of "+ size + " is created."); //TEMP

    }

 

    public void add(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 boolean delete( String searchName )

    {

        boolean    status;

        int        loc;

 

        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

        }

 

        return status;

    }

 

    public Person 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];

        }

 

        return foundPerson;

    }

 

    public Person[ ] sort ( int attribute ) {

 

        if (!(attribute == Person.NAME || attribute == Person.AGE) ) {

            throw new IllegalArgumentException( );

        }

 

        Person[ ] sortedList = new Person[ 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

        int      bottom, 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--;

        }

 

        return sortedList;

    }

 

    private void enlarge( )

    {

        //create a new array whose size is 150% of

        //the current array

        int newLength = (int) (1.5 * entry.length);

        Person[] temp = new Person[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 int findIndex( String searchName )

    {

        int loc = 0;

 

        while ( loc < count &&

                !searchName.equals( entry[loc].getName() ) ) {

            loc++;

        }

 

        if (loc == count) {

 

            loc = NOT_FOUND;

        }

 

        return loc;

    }

 

}

AddressBookVer2类:

package example12;

 

import java.util.*;

 

class AddressBookVer2 implements AddressBook {

 

    private static final int  DEFAULT_SIZE = 25;

 

    private static final int  NOT_FOUND    = -1;

 

    private Person[]  entry;

 

    private int        count;

 

    public AddressBookVer2( ) {

        this( DEFAULT_SIZE );

    }

 

    public AddressBookVer2(int size) {

        count = 0;

 

        if (size <= 0 ) { //invalid data value, use default

            throw new IllegalArgumentException("Size must be positive");

        }

 

        entry = new Person[size];

 

 //      System.out.println("array of "+ size + " is created."); //TEMP

    }

 

    public void add( 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 boolean delete( String searchName ) {

        boolean    status;

        int        loc;

 

        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

        }

 

        return status;

    }

 

    public Person 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];

        }

 

        return foundPerson;

    }

 

    public Person[ ] sort ( int attribute ) {

 

        if (!(attribute == Person.NAME || attribute == Person.AGE) ) {

            throw new IllegalArgumentException( );

        }

 

        Person[ ] sortedList = new Person[ count ];

 

        //copy references to sortedList

        for (int i = 0; i < count; i++) {

            sortedList[i] = entry[i];

        }

 

        Arrays.sort(sortedList, getComparator(attribute));

 

        return sortedList;

    }

 

    private void enlarge( )

    {

        //create a new array whose size is 150% of

        //the current array

        int newLength = (int) (1.5 * entry.length);

        Person[] temp = new Person[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 int findIndex( String searchName )

    {

        int loc = 0;

 

        while ( loc < count &&

                !searchName.equals( entry[loc].getName() ) ) {

            loc++;

        }

 

        if (loc == count) {

 

            loc = NOT_FOUND;

        }

 

        return loc;

    }

 

    private Comparator getComparator(int attribute) {

        Comparator comp = null;

 

        if (attribute == Person.AGE) {

            comp = new AgeComparator( );

 

        } else {

            assert attribute == Person.NAME:

                    "Attribute not recognized for sorting";

 

            comp = new NameComparator( );

        }

 

 

        return comp;

 

    }

 

    class AgeComparator implements Comparator {

 

        private final int LESS = -1;

        private final int EQUAL = 0;

        private final int MORE  = 1;

 

        public int compare(Object p1, Object p2) {

           int comparisonResult;

 

            int p1age = ((Person)p1).getAge( );

            int p2age = ((Person)p2).getAge( );

 

            if (p1age < p2age) {

                comparisonResult = LESS;

            } else if (p1age == p2age) {

                comparisonResult = EQUAL;

            } else {

                assert p1age > p2age;

                comparisonResult = MORE;

            }

 

            return comparisonResult;

        }

    }

 

    class NameComparator implements Comparator {

 

        public int compare(Object p1, Object p2) {

 

            String p1name = ((Person)p1).getName( );

            String p2name = ((Person)p2).getName( );

 

            return p1name.compareTo(p2name);

 

        }

    }

 

}

AddressBookVer3类:

package example12;

 

import java.util.*;

 

class AddressBookVer3 implements AddressBook {

 

    private static final int  DEFAULT_SIZE = 25;

 

    private Map  entry;

 

    public AddressBookVer3( ) {

        this( DEFAULT_SIZE );

    }

 

    public AddressBookVer3(int size) {

        entry = new HashMap(size);

 

 //      System.out.println("array of "+ size + " is created."); //TEMP

    }

 

    public void add( Person newPerson ) {

        entry.put(newPerson.getName(), newPerson);

    }

 

    public boolean delete( String searchName ) {

 

        boolean status;

        Person  p = (Person) entry.remove(searchName);

 

        if (p == null) {

            status = false;

        } else {

            status = true;

        }

 

        return status;

    }

 

    public Person search( String searchName ) {

 

        return (Person) entry.get(searchName);

    }

 

    public Person[ ] sort ( int attribute ) {

 

        if (!(attribute == Person.NAME || attribute == Person.AGE) ) {

            throw new IllegalArgumentException( );

        }

 

       Person[ ] sortedList = new Person[entry.size()];

        entry.values().toArray(sortedList);

 

        Arrays.sort(sortedList, getComparator(attribute));

 

        return sortedList;

    }

 

    private Comparator getComparator(int attribute) {

        Comparator comp = null;

 

        if (attribute == Person.AGE) {

            comp = new AgeComparator( );

 

        } else {

            assert attribute == Person.NAME:

                    "Attribute not recognized for sorting";

 

            comp = new NameComparator( );

        }

 

        return comp;

    }

 

    class AgeComparator implements Comparator {

 

        private final int LESS = -1;

        private final int EQUAL = 0;

        private final int MORE  = 1;

 

        public int compare(Object p1, Object p2) {

            int comparisonResult;

 

            int p1age = ((Person)p1).getAge( );

            int p2age = ((Person)p2).getAge( );

 

            if (p1age < p2age) {

                comparisonResult = LESS;

            } else if (p1age == p2age) {

                comparisonResult = EQUAL;

            } else {

                assert p1age > p2age;

                comparisonResult = MORE;

            }

 

            return comparisonResult;

        }

    }

 

    class NameComparator implements Comparator {

 

        public int compare(Object p1, Object p2) {

 

            String p1name = ((Person)p1).getName( );

            String p2name = ((Person)p2).getName( );

 

            return p1name.compareTo(p2name);

 

        }

    }

 

}

 

 

关键词:排序  通讯  试题  通讯录 

【内容导航】
第1页:源程序 第2页:运行结果
第3页:源程序揭秘
收藏 推荐 打印 | 录入:blue1000 | 阅读:
最新图文
本文评论   查看全部评论 (4)
表情: 姓名: 字数
点评:
       
评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事/刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款
第 4 楼
* 匿名 发表于 2016/12/25 13:31:45
http://www.blue1000.com/bkhtml/c149/2013-09/71322.htm 事假请假条范文 http://www.blue1000.com/show/17003.html 单位事假请假条 http://www.blue1000.com/show/17000.html
第 3 楼
* 匿名 发表于 2016/12/24 19:30:45
http://www.blue1000.com/bkhtml/c149/2013-10/71375p3.htm 2017年七一建党节活动简报 http://www.blue1000.com/show/17066.html 2017年七一建党96周年活动简报 http://www.blue1000.com/show/17065.html
第 2 楼
* 匿名 发表于 2016/12/24 19:30:15
http://www.blue1000.com/bkhtml/c149/2013-09/71324.htm 加薪通知 http://www.blue1000.com/show/2159.html 工作时间调整通知 http://www.blue1000.com/show/2158.html
第 1 楼
* 匿名 发表于 2016/12/24 13:26:39
http://www.blue1000.com/bkhtml/c149/2013-09/71322.htm 宽容的作文 http://www.blue1000.com/details/zs209.html 桃花的作文 http://www.blue1000.com/details/zs212.html