英文:
Getting error The method sort(List<T>) in the type Collections is not applicable for the arguments (List<LinkedInUser>)
问题
@Test
public void sortingTest() throws LinkedInException {
LinkedInUser Han = new LinkedInUser("Han", "hanpass");
LinkedInUser LUKE = new LinkedInUser("LUKE", "LUKEpass");
LinkedInUser leia = new LinkedInUser("leia", "leiapass");
Han.addConnection(LUKE);
Han.addConnection(leia);
List<LinkedInUser> hansConnections = Han.getConnections();
Collections.sort(hansConnections);
hansConnections.get(0).equals(leia);
hansConnections.get(1).equals(LUKE);
}
英文:
@Test
public void sortingTest() throws LinkedInException {
LinkedInUser Han = new LinkedInUser("Han", "hanpass");
LinkedInUser LUKE = new LinkedInUser("LUKE", "LUKEpass");
LinkedInUser leia = new LinkedInUser("leia", "leiapass");
Han.addConnection(LUKE);
Han.addConnection(leia);
List<LinkedInUser> hansConnections = Han.getConnections();
Collections.sort(hansConnections);
hansConnections.get(0).equals(leia);
hansConnections.get(1).equals(LUKE);
}
I am getting an error code with my sort, if anyone could provide insight as to how to fix this issue I would appreciate it.
答案1
得分: 4
这个方法的声明如下:
public static <T extends Comparable<? super T>> void sort(List<T> list)
当你使用List<LinkedInUser>调用时,意味着T是LinkedInUser,这意味着**LinkedInUser 必须 实现Comparable<LinkedInUser>**(或者是LinkedInUser的某个父类型)。
如果你无法做到这一点,可以调用重载版本,以便提供一个Comparator:
public static <T> void sort(List<T> list, Comparator<? super T> c)
如果现在既没有类实现Comparable,也没有提供Comparator,你期望对象按什么顺序排序呢?
英文:
The method is declared as:
public static <T extends Comparable<? super T>> void sort(List<T> list)
When you call with a List<LinkedInUser>, it means that T is a LinkedInUser, which means that LinkedInUser must implement Comparable<LinkedInUser> (or some super-type of LinkedInUser).
If you can't do that, call the overload, so you can supply a Comparator instead:
public static <T> void sort(List<T> list, Comparator<? super T> c)
Right now, without the class implementing Comparable, and without supplying a Comparator, what order did you expect the objects to be sorted in?
答案2
得分: 2
你需要阅读这份Java集合的文档。找到sort方法并查看其工作原理。
你可以做两件事情:
-
在你的
LinkedinUser类中实现Comparable接口并重写compareTo方法,根据你想要对对象进行排序的方式提供其实现。 -
使用
Comparator接口,并实现compare方法(使用匿名接口实现)。
英文:
You need to read this documentation of Java Collections. Find the sort method and check how it works.
You can do two things:
-
Implement
Comparableinterface in yourLinkedinUserclass and overridecompareTomethod, providing its implementation according to which you want to sort objects. -
Use
Comparatorinterface, and implementing thecomparemethod(using Anonymous Interface Implementations)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论