猿问

怎么消除以下两个方法的重复代码?我做了尝试,百度了也不行

以下两个方法传入参数类型不一样,但是处理逻辑是一致的,要怎么才能消除重复代码privatevoidsetStudentExamRank(Listlist){Listtemp=Lists.newArrayListWithCapacity(list.size());temp.addAll(list);temp.sort(Comparator.comparingInt(StudentExam::getScore));StudentExame;for(inti=0;i<temp.size();i++){e=temp.get(i);e.setRank(e.getScore()>0?i+1:0);}}privatevoidsetStudentClassesTestRank(Listlist){Listtemp=Lists.newArrayListWithCapacity(list.size());temp.addAll(list);temp.sort(Comparator.comparingInt(StudentClassesTest::getScore));StudentClassesTeste;for(inti=0;i<temp.size();i++){e=temp.get(i);e.setRank(e.getScore()>0?i+1:0);}}
函数式编程
浏览 516回答 2
2回答

MMTTMM

用继承或接口都可以interfaceGrade{intgetScore();}classStudentExamimplementsGrade{publicintgetScore(){//TODO}}classStudentClassesTestimplementsGrade{publicintgetScore(){//TODO}}privatevoidsetStudentClassesTestRank(Listlist){//...list.sort(Comparator.comparingInt(Grade::getScore));//...}

慕田峪7331174

StudentExam和StudentClassesTest继承同一个父类或实现同一个接口比如Student。然后定义方法:publicvoidsetRank(Studente){for(inti=0;i0?i+1:0);}}调用时传入StudentExam或者StudentClassesTest的实例即可
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答