62,612
社区成员
发帖
与我相关
我的任务
分享
public interface IShowable {
public void show();
}
public class Test {
public void showObject(IShowable obj){
obj.show();
}
class Employee implements IShowable{
@Override
public void show() {
System.out.println("我是员工");
}
}
public IShowable getManager(){
return new IShowable(){
@Override
public void show() {
System.out.println("我是管理员");
}
};
}
public static void main(String[] args) {
Test test = new Test();
IShowable showable1 = test.new Employee();
IShowable showable2 = test.getManager();
test.showObject(showable1);
test.showObject(showable2);
test.showObject(new IShowable() {
@Override
public void show() {
System.out.println("我是匿名内部类");
}
});
}
}
是这样的吗?
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Student implements Comparable {
private int id;
private String name;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public int compareTo(Object object) {
if(object != null && object instanceof Student){
Student student = (Student)object;
return (int)(this.birthday.getTime() - student.birthday.getTime());
}
return 0;
}
@Override
public String toString() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return this.getId() + " ; " +this.getName() + " ; " + df.format(this.getBirthday());
}
}
import java.util.Arrays;
import java.util.Calendar;
public class ComparableStudent {
/**
* @param args
*/
public static void main(String[] args) {
Student[] students = new Student[10];
Calendar calendar = Calendar.getInstance();
for(int i = 0 ; i < 10 ; i++){
Student student = new Student();
student.setId(i);
student.setName("name" + i);
calendar.add(calendar.DAY_OF_MONTH, i);
student.setBirthday(calendar.getTime());
students[9-i] = student;
}
System.out.println("排序前......");
for(Student student : students){
System.out.println(student);
}
System.out.println("排序后......");
Arrays.sort(students);
for(Student student : students){
System.out.println(student);
}
}
}
这道题目考察你compareTo方法比较两个对象
if(object != null && object instanceof Student)
这个判断语句判断要比较的对象不为null,并且是Student的实例,这样才可以向下转型为Student
Student student = (Student)object;也就是这句话
compareTo方法返回一个int值
如果A和B比较,A在前的话,返回负数,B在前返回整数,相等返回0
其实Date对象实现了compareTo方法
你也可以这样写
this.getBirthday().compareTo(student.getBirthday());
我那么写并不好,但是希望你明白怎么比较的!