按名字升序排列报错
sort处提示:
The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (List<Cat>, NameComparator)
3
收起
正在回答
2回答
你好!你的代码在我这里是可以运行正确的,调试后的所有代码如下。建议同学下次贴代码时也像我一样,把代码忒到回答里,不截图,这样方便我们快速为你解答。
Cat类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | package com.imooc.sort; public class Cat { private String name; private int age; private String specis; public Cat(){} public Cat(String name, int age, String specis) { super (); this .name = name; this .age = age; this .specis = specis; } 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 String getSpecis() { return specis; } public void setSpecis(String specis) { this .specis = specis; } @Override public String toString() { return "Cat [name=" + name + ", age=" + age + ", specis=" + specis + "]" ; } } |
NameComparator类:
1 2 3 4 5 6 7 8 9 10 11 12 13 | package com.imooc.sort; import java.util.Comparator; public class NameComparator implements Comparator<Cat> { @Override public int compare(Cat arg0, Cat arg1) { // 按宠物猫名字进行升序排列 // 如果降序排列:arg1.getName().compareTo(arg0.getName()); String name1=arg0.getName(); String name2=arg1.getName(); int n= name1.compareTo(name2); return n; } } |
NameTest类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package com.imooc.sort; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class NameTest { public static void main(String[] args) { Cat huahua= new Cat( "huahua" , 3 , "英国短毛猫" ); Cat fanfan= new Cat( "fanfan" , 5 , "中华田园猫" ); Cat maomao= new Cat( "maomao" , 1 , "中华田园猫" ); List<Cat> catList= new ArrayList<Cat>(); catList.add(huahua); catList.add(fanfan); catList.add(maomao); System.out.println( "按名字升序排序前:" ); for (Cat cat:catList){ System.out.println(cat); } Collections.sort(catList, new NameComparator()); System.out.println( "按名字升序排序后:" ); for (Cat cat:catList){ System.out.println(cat); } } } |
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题
登录后可查看更多问答,登录/注册
1. Java 零基础入门
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧