`
thinkingmt
  • 浏览: 23820 次
  • 性别: Icon_minigender_1
  • 来自: 桂林
社区版块
存档分类
最新评论

About "sort of the objects"

阅读更多

      今天完成了一个小工程,这个工程的功能是对学生进行管理,可以添加,删除,修改成绩,使学生按不同规则进行排序(我所实现的是按照studentName 和 averageScore进行排序)。

 

      以前所能做到的只是对例如int,double等的基本数据类型进行比较,排序。现在可以利用对类实现Comparable<T>接口来达到对对象的比较排序的目的,其中,T 表示可以与此对象进行比较的那些对象的类型。一个很典型的例子就是String这个类,String实现了Comparable<String>这个接口,并对其唯一的抽象方法:compareTo()进行重写,使两个String可以比较,排序。

 

      现如今,我们将此构架移植到Student这个工程中,实现排序功能。

 

----------------------------------------------------------------------------------------------------------------------------------

 

代码如下:

 

第一个类:

 

public class Student implements Comparable<Student>
{
    private String studentNumber;
    private String studentName;
    private int markForMaths;
    private int markForEnglish;
    private int markForScience;
    private double averageScore;
    private static int sortType;
    
    public Student(String number,String name)
    {
        studentNumber=number;
        studentName=name;
    }
    
    public String getNumber()
    {
        return studentNumber;
    }
    
    public String getName()
    {
        return studentName;
    }
    
    public void enterMarks(int maths,int english,int science)
    {
        markForMaths=maths;
        markForEnglish=english;
        markForScience=science;
        calculateAverageMark();
    }
    
    public int getMathsMark()
    {
        return markForMaths;
    }
    
    public int getEnglishMark()
    {
        return markForEnglish;
    }
    
    public int getScienceMark()
    {
        return markForScience;
    }
    
    public double calculateAverageMark()
    {
        averageScore=(markForMaths+markForEnglish+markForScience)/3.0;
        return averageScore;
    }
    
    public String toString()
    {
        String showMessage="StudentNumber is:"+getNumber()+"\n"+"StudentName is:"+getName()+"\n";
        showMessage+="AverageMark is"+calculateAverageMark()+"\n";
        showMessage+="-------------------------------------";
        
        return showMessage;
    }
    
    public static void setSortType(int number)
    {
        sortType=number;
    }
    
    public int compareTo(Student stu)
    {
        if(sortType==1)// sort by the average mark
        {
            if(calculateAverageMark()>stu.calculateAverageMark())
            {
                return -1;
            }
            
            else if(calculateAverageMark()<stu.calculateAverageMark())
            {
                return 1;
            }
            
            else
            return 0;
        }
        
        else if(sortType==2)// sort byt the name index
        {
            int  num =getName().compareTo(stu.getName());
            if(num>0)
            {
                return 1;
            }
            
            else if (num<0)
            {
                return -1;
            }
            
            else
            return 0;
        }
        
        return 0;
    }
}

 

 

compareTo()这个方法中,就是对比较规则进行规定(specify the rules of sort),由于这个方法是重写的,所以方法必定有参数(接口Comparable中的compareTo(T o)就有参数,根据overriding,此类的compareTo()也必须有参数)。

 

如果想实现各种各样的不同规则的排序,就需要定义一个类变量sortType来指定排序的类型,此例中:1.表示按照学生的平均成绩进行排序  2.表示按学生的名字进行排序。

 

第二个类:

 

import java.util.*;

public class StudentManager
{
    private ArrayList<Student> stu;
    
    public StudentManager()
    {
        stu=new ArrayList<Student>();
    }
    
    public void addStudent(String name)
    {
        int numberOfStudent=stu.size()+1;
        String number="J-BCU";
        if(numberOfStudent<10)
        {
            number=number+"00"+numberOfStudent;
        }
        else if(numberOfStudent>10)
        {
            number=number+"0"+numberOfStudent;
        }
        Student t= new Student(number,name);
        stu.add(t);
    }
    
    public void removeStudent(String number)
    {
        Student removeOne =findStudent(number);
        if(removeOne!=null)
        {
            stu.remove(removeOne);
        }
    }
    
    public Student findStudent(String number)
    {
        for(Student student:stu)
        {
            if((student.getNumber()).equals(number))
            {
                return student;
            }
        }
        
        return null;
    }
    
    public void showAllStudent()
    {
        for(Student student:stu)
        {
            System.out.println(student);
        }
    }
    
    public void inputMark(String number,int math,int enl,int sci)
    {
        Student inputOne= findStudent(number);
        if(inputOne !=null)
        {
            inputOne.enterMarks(math,enl,sci);
        }
    }
    
    public void sortByAverage()
    {
        int sortAverage=1;//1 means the sort type is sorted by the average mark of student.
        Student.setSortType(sortAverage);
        Collections.sort(stu);
    }
    
    public void sortByName()
    {
        int sortName=2;//2 means the sort tyoe is sorted by the name index.
        Student.setSortType(sortName);
        Collections.sort(stu);
    }
}

 

 

这个通过利用ArrayList来对学生进行管理,在sortByAverage()和sortByName()两个方法中,通过对Student的静态方法setSortType(sortAverage)的调用改变排序类型,然后利用java.util.Collections

 

public static <T extends Comparable<? super T>> void sort(List<T> list)

 

的调用,在此例中:是Collections.sort(stu);

注意:

                 1)列表中的所有元素都必须实现 Comparable 接口。此外,列表中的所有元素都必须是可相互比较的(也就是说,对于列表中的任何 e1e2 元素,e1.compareTo(e2) 不得抛出 ClassCastException)。

 

                 2)指定列表必须是可修改的,但不必是大小可调整的。

 

----------------------------------------------------------------------------------------------------------------------------------

 

通过以上操作,即对对象进行了排序。

 

如果是对象们存放在array中,用类Arrays 的 sort方法。

如果是对象们存放在list中,    用Collections的 sort方法。

 

 

 

分享到:
评论

相关推荐

    About \"sort of the objects\"

    NULL 博文链接:https://thinkingmt.iteye.com/blog/971195

    VB6_逆向工程.pdf

    can easily extract all the information you need about all components of the program. To analyze a VB application I used this program that was written by a friend of mine (thank you _d31m0s_!). It’s a...

    Ray Wenderlich - iOS 11 Tutorials

    ARKit: Augmented reality programming without some sort of help can be very difficult. As a developer you need to figure out where your “virtual” objects should be placed in the “reality” view, how...

    learn sprite kit for game development

    nnIn Chapter 6, we’ll present one way to create a sort of “cast of characters” that will handle the timing and spawning of bad guys and bonuses. You don’t want everyone showing up on stage all at ...

    Python Data Structures and Algorithms [2017]

    The book will explore in detail sorting algorithms such as bubble sort, selection sort, insertion sort, and merge sort. By the end of the book, you will learn how to build components that are easy ...

    ehlib_vcl_src_9_3.26

    More detail about new features in this version of the library can be found in the file - About EhLib 9.2 Eng.doc To install a new version of the library in the IDE, use the installation program .\...

    算法导论--Introduction.to.Algorithms

    About the Author Thomas H. Cormen is Professor of Computer Science and former Director of the Institute for Writing and Rhetoric at Dartmouth College. Charles E. Leiserson is Professor of Computer ...

    EhLib 9.1.024

    More detail about new features in this version of the library can be found in the file - About EhLib 9.1 Eng.doc To install a new version of the library in the IDE, use the installation program .\...

    DiskControls_XE5

    Several components that provide you with detailed information about any shell objects (files, folders or drives), can retrieve the version information from executable files and dynamic-link libraries;...

    Foundations of Agile Python Development (2008).pdf

    You can’t replicate your work for testing purposes without some sort of a framework. In Python, a natural choice is Setuptools,which provides a solid basis for automated builds. Chapter 5:A Build for...

    微软内部资料-SQL性能优化3

    In our example, if one transaction (T1) holds an exclusive lock at the table level, and another transaction (T2) holds an exclusive lock at the row level, each of the transactions believe they have ...

    netWindows_0.3.0_pre2

    Alex would like to thank Mark Anderson of Discerning Software for his invaluable help, advice, prodding, probing questions, incredible support, and persistant push that has made this release the giant...

    EhLib 8.0 Build 8.0.023 Pro Edition FullSource for D7-XE8

    DataDriver that have four objects of the TSQLCommandEh type: SelectCommand, DeleteCommand, InsertCommand, UpdateCommand, GetrecCommand. TSQLDataDriverEh can not transfer queries to the server but ...

    BobBuilder_app

    In the event of page getting full and reaching the PageItemCount, MGIndex will sort the keys in the page's dictionary and split the data in two pages ( similar to a b+tree split) and update the page ...

    EhLib 6.3 Build 6.3.176 Russian version. Full source included.

    DataDriver that have four objects of the TSQLCommandEh type: SelectCommand, DeleteCommand, InsertCommand, UpdateCommand, GetrecCommand. TSQLDataDriverEh can not transfer queries to the server but ...

    Python Cookbook英文版

    2.6 Sorting a List of Objects by an Attribute of the Objects 2.7 Sorting by Item or by Attribute 2.8 Selecting Random Elements from a List Without Repetition 2.9 Performing Frequent Membership ...

    EhLib5.0.13 最新的ehlib源码

    DataDriver that have four objects of the TSQLCommandEh type: SelectCommand, DeleteCommand, InsertCommand, UpdateCommand, GetrecCommand. TSQLDataDriverEh can not transfer queries to the server but ...

    Everyday Data Structures

    Unleash the power of different sorting techniques such as bubble sort, quick sort, merge sort, insertion sort, and radix sort Perform searching operations on arrays, heaps, graphs, and binary trees in...

    Program in LUA 2nd Edition.rar

    7.2 The Semantics of the Generic for 57 7.3 Stateless Iterators 58 7.4 Iterators with Complex State 60 7.5 True Iterators 61 8 Compilation, Execution, and Errors 63 8.1 Compilation 63 8.2 C Code...

Global site tag (gtag.js) - Google Analytics