调用一个方法时,向该方法除了传数据之外,还要向该方法中传一段代码,并且在该方法中调用这段代码(这段代码一般在接口里定义,在匿名类里实现)。
学生筛选系统:
public class Student {
private String name;
private int age;
private double score;
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String toString(){
return name;
}
}
定义一个学生筛选器:
public interface StudentFilter {
public abstract boolean accept(Student student);
}
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Student> list=new ArrayList<Student>();
list.add(new Student("xu",45,45.1));
list.add(new Student("yu",12,81.0));
//将过滤器传输给selector方法
List <Student> listTest=selector(list,new StudentFilter(){
@Override
public boolean accept(Student student) {
if(student.getScore()>80.0){
return true;
}
return false;
}
});
System.out.println(listTest);
}
public static List<Student> selector(List<Student> list,StudentFilter filter){
List<Student> listStudent=new ArrayList<Student>();
for(Student stu:list){
if(filter.accept(stu)){
listStudent.add(stu);
}
}
return listStudent;
}
}