0

I have some models which implement an interface, i.e. they all implement a specific method, let's call it method "A". Now I have a class with method "B" which is supposed to call method "A". So I defined it so it gets the interface as an input argument, and all is well. The problem is when I give the models (which implement the interface) to method "B", it says the types are different.

I tried casting the models to the interface, it gives me the "incompatible types" error.

Here is what I have:

public interface BaseObject<T> {
    boolean isEqualTo(T object); //AKA: method "A"
}

public interface BaseList<T extends BaseObject> {
    boolean areListsEqual(List<T> firstList, List<T> secondList);  //AKA: method "B"
}

public class Helper implements BaseList<BaseObject> {

    @Override
    public boolean areListsEqual(List<BaseObject> firstList, List<BaseObject> secondList) {
        boolean isEqual = true;
        ...
        for (int i = 0; i < firstList.size(); i++) {
                isEqual = isEqual && firstList.get(i).isEqualTo(secondList.get(i));
        }

        return isEqual;
        ...
      }
}

// I have different ones
public class MyModel implements BaseObject<MyModel>{
...
}

And here's the part which I get the errors:

List<MyModel> first = new ArrayList<>(): 
List<MyModel> second = new ArrayList<>(): 
...
new Helper().areListsEqual(first, second);

// This is another thing I tried
new Helper().areListsEqual((List<BaseObject>) first, (List<BaseObject>) second);

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
e.y66
  • 99
  • 10

1 Answers1

0

So I found a solution. I had to convert the list. I added the method to Helper class and converted each list before giving it to "areListsEqual" method. Here's how it goes:

    public List<BaseObject> convertList(List inputList){
        List<BaseObject> baseList = new ArrayList<>();

        if (inputList != null && inputList.size() > 0)
            baseList.addAll(inputList);

        return baseList;
    }

And this is how I call it:

Helper helper = new Helper();
helper.areListsEqual(helper.convertList(first), helper.convertList(second));

e.y66
  • 99
  • 10