Reputation: 4660
This is probably a java 101 question. But I've been away from java for ten years, so it's new to me.
I have 3 classes: Dog, Cat, Mouse
Each has its own ArrayList e.g., ArrayList<Dog> dogs = new ArrayList<Dog>();
Dog Cat and Mouse implement AnimalInterface (which has methods such as getFurColor() and setFurColor(Color c)).
I have a method called, say, changeFurColor(ArrayList <AnimalInterface>list).
Moreover, changeFurColor() sorts the input ArrayList using a comparator that implements <AnimalInterface> so I need this parameterized type in my changeFurColor() method.
I call the method with changeFurColor(dogs);
However, this won't compile. The type <Dog> does not match the type <AnimalInterface> even though the former implements the latter.
I know I can simply use ? as the type for the changeFurColor argument and then cast or do instance of within the method as a check, but then I can't sort the list with my comparator (and it seems silly to have 3 different comparators).
I can't type all ArrayLists with <AnimalInterface> because I don't want to risk a dog in with the cats.
I am sure there is a simple solution, but none of my books provide it and I can't find it online
pseudoCode:
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)
{
...
}
}
UPDATE changeFurColor(dogs) does not compile
Upvotes: 2
Views: 115
Reputation: 4660
This is the correct answer (for neophytes that follow me)
Credit goes to Solitirios for his comment on the question.
public static <T extends AnimalInterface> void changeFurColor(ArrayList<T> list) –
Upvotes: 1
Reputation: 200
I don't see any issues in the design.I'd need the exact code to tell what's exactly wrong, but The possible errors are:
You are not implementing the AnimalInterface method in the animal classes (Dog,Cat..), the method need's to be implemented explicitly:
class Dog implements AnimalInterface{public Color getColor(){return new Color();}}
class Cat implements AnimalInterface{public Color getColor(){return new Color();}}
You are passing a Comparator class, insteads of a instance in the Collections.sort method:
Collections.sort(list, MyAnimalFurComparator);
You need to change it to this:
Collections.sort(list,new MyAnimalFurComparator());
Also the compare method of your MyAnimalFurComparator should return an int
Upvotes: 0