这可能是一个java 101问题。但是我已经离开java十年了,所以对我来说这是新的。
我有3个班级:狗,猫,老鼠
每个都有自己的ArrayList 例如,ArrayList< Dog> dogs = new ArrayList< Dog>();
Dog Cat and Mouse实现了AnimalInterface(其中包含getFurColor()和setFurColor(Color c)等方法)。
我有一个名为changeFurColor(ArrayList< AnimalInterface> list)的方法。
此外,changeFurColor()使用实现< AnimalInterface>的比较器对输入ArrayList进行排序。所以我需要在我的changeFurColor()方法中使用这个参数化类型。
我用changeFurColor(dogs)调用方法;
但是,这不会编译。类型< Dog>与类型< AnimalInterface>不匹配即使前者实现了后者。
我知道我可以简单地使用?作为changeFurColor参数的类型然后在方法中强制转换或执行实例作为检查,但是我不能用我的比较器对列表进行排序(并且有3个不同的比较器似乎很愚蠢)。
我无法使用< AnimalInterface>键入所有ArrayLists因为我不想让狗和狗一起冒险。
我确信有一个简单的解决方案,但我的书都没有提供它,我无法在网上找到它
伪代码:
public interface AnimalInterface
{
public Color getColor();
......
}
public class Dog implements AnimalInterface
{
}
public class Cat implements AnimalInterface
{
}
public void example()
{
ArrayList<Dog> dogs = new ArrayList<Dog>();
ArrayList<Cat> cats = new ArrayList<Cat>();
ArrayList<Mouse> mice = new ArrayList<Mouse>();
changeFurColor(dogs)
}
public void changeFurColor(ArrayList <AnimalInterface> list)
{
... ..
Collections.sort(list, MyAnimalFurComparator);
}
public class MyAnimalFurComparator implements Comparator<AnimalInterface>
{
@Override
public int compare(AnimalInterface o1, AnimalInterface o2)
{
...
}
}
更新 changeFurColor(dogs)无法编译
答案 0 :(得分:1)
这是正确的答案(对于跟随我的新手)
感谢Solitirios对这个问题的评论。
public static <T extends AnimalInterface> void changeFurColor(ArrayList<T> list) –
答案 1 :(得分:0)
我没有看到设计中的任何问题。我需要确切的代码来说明确切的错误,但可能的错误是:
您没有在动物类(Dog,Cat ..)中实现AnimalInterface方法,需要明确实现方法:
class Dog implements AnimalInterface{public Color getColor(){return new Color();}}
class Cat implements AnimalInterface{public Color getColor(){return new Color();}}
您正在传递Comparator类,而不是Collections.sort方法中的实例:
Collections.sort(list, MyAnimalFurComparator);
您需要将其更改为:
Collections.sort(list,new MyAnimalFurComparator());
MyAnimalFurComparator的比较方法也应该返回一个int