是这样 我在Student类中定义了一个私有类SortMethod,它实现了Comparator<Student>接口,覆盖了方法compare(T t1,T t2),在MainTest测试主类调用Collections.sort(List<T> t,Comparator<T> com).现在我想在Student类中直接获取该类的一个实例,直接传给MainTest类中Collections.sort()方法。问题出来了,该如何通过Student类来获取SortMethod的对象。我仿造c#的方法。结果行不通。下面是代码,红色字体部分。望不吝解析,谢谢!!- import java.util.Comparator;
- class Student implements Comparable<Student> {
- private String stuname;
- private int maths;
- private int ens;
- private int phs;
- private int sum;
- public Student(){}
- public Student(String name,int maths,int ens,int phs ) {
- this.stuname=name;
- this.maths=maths;
- this.ens=ens;
- this.phs=phs;
- sum=maths+ens+phs;
- }
- public String getStuName(){
- return this.stuname;
- }
- public int getSum(){
- return this.sum;
- }
- public int compareTo(Student stu){
- if(this.sum>stu.sum)
- return 1;
- if(this.sum<stu.sum)
- return -1;
- else
- return 0;
- }
- public int hasCode(){
- return this.stuname.hashCode()+sum*12;
- }
- public boolean equals(Object obj){
- if(!(obj instanceof Student))
- {
- throw new ClassCastException("类型不匹配");
- }
- Student student=(Student)obj;
- return this.stuname.equals(student.stuname)&&this.sum==student.sum;
-
- }
- public String toString(){
- return "学生信息:"+this.stuname+"----"+this.sum;
- }
- <font color="red">private class SortMethod implements Comparator<Student>{
- public int compare(Student stu1,Student stu2){
- return stu1.stuname.compareTo(stu2.stuname);
- }
- <font color="blue">//这是我仿造c#写的获取类SortMethod对象的方法,该行报错
- </font> public static Comparator<Student> getInstance{
- get{ return new SortMethod();};
- <font color="#0000ff">/*别告诉我这样 public Comparator<Student> getInstance(){
- return new SortMethod()},这样没法在类外通过Student类名调用*/</font> </font>
- }
- }
复制代码 |
|