这是我的Item类,它实现了Thing(我的界面)
package moving.domain;
public class Item implements Thing, Comparable<Thing>{
private int volume;
private String name;
public Item (String name, int vol) {
this.name = name;
this.volume = vol;
}
public String getName() {
return this.name;
}
@Override
public int getVolume() {
return this.volume;
}
@Override
public String toString() {
return this.getName() + " (" + this.getVolume() + " dm^3)";
}
@Override
public int compareTo(Thing t) {
return (int) Integer.compare(this.getVolume(),(t.getVolume())); //To change body of generated methods, choose Tools | Templates.
}
这是界面
package moving.domain;
public interface Thing {
int getVolume();
}
这是主要方法
package moving;
import java.util.Collections;
import java.util.List;
import moving.domain.Item;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import moving.domain.Thing;
public class Main {
public static void main(String[] args) {
// test your program here
Map<String, Thing> items2 = new HashMap<String, Thing>();
//storing interface type Thing in hashmap as value
items2.put("three", new Item("passport", 2));
items2.put("two", new Item("toothbrash", 1));
items2.put("one", new Item("circular saw", 100));
List<Thing> items3 = new ArrayList<Thing>(items2.values());
Collections.sort(items3);
//
System.out.println(items3);
}
}
当我尝试对集合进行排序时,我收到以下错误:
no suitable method found for sort(List<Thing>)
method Collections <T#1>sort<List<T#1>) is not applicable
(inferred type does not conform to upper bounds(s)
inferred: Thing
upper bounds(s) Comparable <? super Thing>)
method Collections<T#2>sort(List<T#2>,Comparator<?superT#2>)is not applicable
(cannot infer type - variables T#2
(actual and formal argument lengths differ in length)
where T#1,T#2 are type variables:
T#1 extends comparable <?super T#1> declared in method <T#1>sort(List<T#1>)
t#2 extends object declared in method <t#2>sort(List<t#2>, Comparator<?super t#2>)
当我尝试创建相同的程序时,我遇到了同样的错误,如以下第45节所示:https://materiaalit.github.io/2013-oo-programming/part2/week-9/
然后,我在上面的代码中重新创建了相同的情况,看看它是否再次发生并且确实发生了。它真的让我烦恼,我似乎无法理解问题所在。最后,我甚至复制并粘贴了第45节中的所有代码,它仍然给出了相同的错误,并在此处给出了它。可以使用接口引用对接口类型进行排序吗?我错过了一些明显的东西吗如果我将所有类型声明更改为Item,则可以正常工作。
public class Main {
public static void main(String[] args) {
// test your program here
List<Thing> items = new ArrayList<Thing>();
items.add(new Item("passport", 2));
items.add(new Item("toothbrash", 1));
items.add(new Item("circular saw", 100));
Collections.sort(items);
System.out.println(items);
}
当我创建一个ArrayList的东西时,我得到了同样的错误,如上所述。
答案 0 :(得分:1)
您的错误发生是因为Thing
不一定是Comparable
。您制作的唯一课程同时实现Thing
和Comparable<Thing>
,但您可以轻松创建:
public class UncomparableThing implements Thing { /* ... */ }
不是Comparable
。它说明了编译器在您尝试对List<Thing>
进行排序时看到的可能性。 Thing
不一定是Comparable
。
如果您愿意,可以将列表更改为List<Item>
,因为您已将Item
定义为Comparable
。或者,您可以使Thing
接口扩展Comparable<Thing>
。另一个选择是将Comparator<Thing>
作为第二个参数传递给Collections.sort
,作为比较不是Comparable
的对象的方法。